𝗝𝗮𝘃𝗮 𝟮𝟱: 𝗝𝗮𝘃𝗮 𝗙𝗹𝗶𝗴𝗵𝘁 𝗥𝗲𝗰𝗼𝗿𝗱𝗲𝗿 (𝗝𝗙𝗥) - 𝗝𝗘𝗣 𝟰𝟳𝟯 𝗣𝗿𝗼𝗺𝗲𝘁𝗵𝗲𝘂𝘀 𝗘𝗻𝗱𝗽𝗼𝗶𝗻𝘁 - 𝗣𝗮𝗿𝘁 𝟮 Starting with Java 25, the 𝚓𝚍𝚔.𝚓𝚏𝚛.𝚙𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜 module is part of the official JDK distribution and when you enable the feature with: -𝚇𝚇:+𝙴𝚗𝚊𝚋𝚕𝚎𝙹𝙵𝚁𝙿𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜𝙴𝚡𝚙𝚘𝚛𝚝𝚎𝚛 𝗧𝗵𝗲 𝗝𝗩𝗠: • Starts JFR internally • Creates a small embedded HTTP server running inside the JVM process • Connects this server to the JFR event stream • And exposes everything through a local HTTP endpoint The local server listens on the default port 𝟳𝟬𝟵𝟭: 𝚑𝚝𝚝𝚙://𝚕𝚘𝚌𝚊𝚕𝚑𝚘𝚜𝚝:𝟽𝟶𝟿𝟷/𝚖𝚎𝚝𝚛𝚒𝚌𝚜 🚫 𝗡𝗼 𝗲𝘅𝘁𝗿𝗮 𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝗶𝗲𝘀 • No Java code needed in your application • No libraries required (𝚒𝚘.𝚖𝚒𝚌𝚛𝚘𝚖𝚎𝚝𝚎𝚛, 𝚓𝚍𝚔.𝚓𝚏𝚛.𝚌𝚘𝚗𝚜𝚞𝚖𝚎𝚛, etc.) • And no sidecar process needed It is entirely internal to the JVM process, implemented in 𝗻𝗮𝘁𝗶𝘃𝗲 𝗖++ 𝗰𝗼𝗱𝗲, running inside the runtime itself. 💡 𝗪𝗵𝗮𝘁 𝘁𝗵𝗲 𝗲𝘅𝗽𝗼𝗿𝘁𝗲𝗿 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗱𝗼𝗲𝘀 Inside the JVM, the exporter behaves like an 𝗼𝗯𝘀𝗲𝗿𝘃𝗲𝗿 of the JFR event stream, with a very lightweight polling loop: • JFR collects events (such as GC, CPU, Threads, Safepoints, etc.) in a 𝗰𝗶𝗿𝗰𝘂𝗹𝗮𝗿 𝗯𝘂𝗳𝗳𝗲𝗿 • The exporter reads these events periodically • It converts them into 𝗰𝘂𝗺𝘂𝗹𝗮𝘁𝗶𝘃𝗲 𝗺𝗲𝘁𝗿𝗶𝗰𝘀 (in OpenMetrics/Prometheus format) • It publishes them via HTTP — 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗮𝗻𝘆𝘁𝗵𝗶𝗻𝗴 𝘁𝗼 𝗱𝗶𝘀𝗸 Metrics are exposed in real time, without any file I/O overhead. ⚙️ 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻 Everything is controlled through 𝗝𝗩𝗠 𝗼𝗽𝘁𝗶𝗼𝗻𝘀, for example: 𝚓𝚊𝚟𝚊 \ -𝚇𝚇:𝚂𝚝𝚊𝚛𝚝𝙵𝚕𝚒𝚐𝚑𝚝𝚁𝚎𝚌𝚘𝚛𝚍𝚒𝚗𝚐=𝚗𝚊𝚖𝚎=𝚙𝚛𝚘𝚍, 𝚜𝚎𝚝𝚝𝚒𝚗𝚐𝚜=𝚙𝚛𝚘𝚏𝚒𝚕𝚎, 𝚖𝚊𝚡𝚊𝚐𝚎=𝟸𝚑, 𝚖𝚊𝚡𝚜𝚒𝚣𝚎=𝟻𝟶𝟶𝙼, 𝚍𝚞𝚖𝚙𝚘𝚗𝚎𝚡𝚒𝚝=𝚏𝚊𝚕𝚜𝚎 \ -𝚇𝚇:+𝙴𝚗𝚊𝚋𝚕𝚎𝙹𝙵𝚁𝙿𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜𝙴𝚡𝚙𝚘𝚛𝚝𝚎𝚛 \ -𝙳𝚓𝚍𝚔.𝚓𝚏𝚛.𝚙𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜.𝚙𝚘𝚛𝚝=𝟽𝟶𝟿𝟷 \ -𝙳𝚓𝚍𝚔.𝚓𝚏𝚛.𝚙𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜.𝚙𝚊𝚝𝚑=/𝚖𝚎𝚝𝚛𝚒𝚌𝚜 \ -𝙳𝚓𝚍𝚔.𝚓𝚏𝚛.𝚙𝚛𝚘𝚖𝚎𝚝𝚑𝚎𝚞𝚜.𝚙𝚎𝚛𝚒𝚘𝚍=𝟹𝟶𝚜 ⚡ 𝗖𝗣𝗨 𝗮𝗻𝗱 𝗺𝗲𝗺𝗼𝗿𝘆 𝗼𝘃𝗲𝗿𝗵𝗲𝗮𝗱 Unfortunately, I haven't had the opportunity to test it in production yet, so we don't know the real overhead of this new feature.... But, in practice, you should not need to disable JFR and it’s common to keep it always active and only 𝗮𝗱𝗷𝘂𝘀𝘁 𝘁𝗵𝗲 𝗹𝗲𝘃𝗲𝗹 𝗼𝗳 𝗱𝗲𝘁𝗮𝗶𝗹 when an incident occurs (via 𝚓𝚌𝚖𝚍). #Java #Java25 #JFR #𝗝𝗮𝘃𝗮𝗙𝗹𝗶𝗴𝗵𝘁𝗥𝗲𝗰𝗼𝗿𝗱𝗲𝗿 #Profiling #Performance #Observability
Java 25: JFR Recorder (JFR) - JEP 323: End-Point - Part 2
More Relevant Posts
-
🚀 Solving Binary WebSocket Challenges in Java + Spring Boot Recently, while implementing a real-time WebSocket app, I ran into a subtle but important challenge with binary messages. ✅ The Problem: ------------------ Sending text messages works fine: session.sendMessage(new TextMessage(payload)); But binary messages (like numbers or files) cannot be sent directly like text. Reusing the same ByteBuffer for multiple sends caused partial or corrupted messages, and using the sender’s session in a broadcast loop sent messages only back to the sender. 🔧 How I Solved It: --------------------- Server-side: =========== byte[] bytes = new byte[payload.remaining()]; payload.get(bytes); // Broadcast to all users safely for (WebSocketSession userSession : userSessionMap.values()) { if (userSession.isOpen()) { userSession.sendMessage(new BinaryMessage(ByteBuffer.wrap(bytes))); // new buffer each time } } Why this matters: ----------------- ByteBuffer position changes after read → must create a new buffer for each send. Use userSession.sendMessage(), not session.sendMessage(), to broadcast to all users. Client-side: ========== ws.binaryType = "arraybuffer"; // receive binary as ArrayBuffer const view = new DataView(event.data); const value = view.getUint32(0, false); // read numeric value correctly ws.binaryType = "arraybuffer" tells the browser how to handle incoming binary data. DataView ensures you read the exact number/value sent from the server. 💡 Key Takeaways: =================== Binary data requires careful handling on both server and client sides. Small details like buffer reuse and proper client interpretation can make or break real-time apps. Solving these edge cases gave me deeper insight into Java NIO, WebSocket protocols, and frontend-backend integration. #Java #SpringBoot #WebSocket #BinaryData #RealTime #FullStack #ProblemSolving #TechnicalSkills #mohacel #mohacelhosen
To view or add a comment, sign in
-
-
Java ke woh secrets jo accidentally discover hue the! 🔥 --- Post 1: Java ka "Accidental Recursive Generics" bug!🤯 ```java public class QuantumBug<T extends QuantumBug<T>> { // Ye pattern originally Eclipse IDE ke internal code mein tha // Josh Bloch ne accidentally discover kiya tha! public T getSelf() { return (T) this; // ClassCastException kabhi nahi aayegi! } } // Usage: class MyClass extends QuantumBug<MyClass> { } // Ye recursive generic bound Java designers ne intentionally nahi banaya tha! ``` Secret: Ye pattern Java Collections Framework mein Enum<E extends Enum<E>> ke liye use hota hai! 💀 --- Post 2: Java ka "Double Colon Operator" ka internal hack!🔥 ```java public class DoubleColonMagic { public static void main(String[] args) { // System::exit actually yeh hai: // (args) -> System.exit(args) // Par internally Java yeh karta hai: // invokedynamic #0:accept:(Ljava/lang/invoke/MethodHandles$Lookup; // Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle; // Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; // Method reference ka bytecode directly lambda se different hai! } } ``` Compiler Accident: Method references lambdas se fundamentally different compile hote hain! 💡 --- Post 3: Java ka "Interface Private Methods" ka hidden conflict!🚀 ```java public interface PrivateMethodConflict { private void secret() { System.out.println("Private in interface - Java 9+"); } // Java designers ko ye add karte waqt pata nahi tha ki: // 1. Ye inheritance mein participate nahi karte // 2. Par fir bhi default methods inhe call kar sakte hain // 3. Ye diamond problem ko complicate karte hain! default void useSecret() { secret(); // ✅ Chalega - par ye design decision controversial tha! } } ``` Design Conflict: Java team 2 saal tak debate karti rahi private interface methods ko add karne se pehle! 💪 --- Post 4: Java ka "Boolean Array" ka memory layout paradox!🔮 ```java public class BooleanArrayParadox { public static void main(String[] args) { boolean[] arr = new boolean[1000]; // Boolean array actually 1 byte per element use karta hai // Na ki 1 bit! - Ye performance optimization ke liye kiya gaya System.out.println("Memory: " + java.lang.management.ManagementFactory.getMemoryMXBean() .getHeapMemoryUsage().getUsed()); // Boolean[] (object array) vs boolean[] (primitive array) // dono ka memory layout different hai! } } ``` Performance Accident: Boolean arrays 1 byte use karte hain kyunki bit manipulation slow hoti hai! 💀 --- yeh accidental discoveries Java team ko bhi surprise karti hain! 😎
To view or add a comment, sign in
-
Hello Everyone, Todays topic is struct, interface Comparing with java, we have the extends for extending the classes and implements for interfaces so similar to that, for denoting the function belongs to this struct, we mention the class name first and then the function name As always i have prepared a cheat sheet for your reference, just a bit of scrolling is required to go through it once. // You can edit this code! // Click here and start typing. package main import "fmt" func main() { e := Employee{ Person: Person{ Name: "Suraj", Age: 25, }, EmployeeID: "E1010", Department: "Finance", } fmt.Println("Name : ", e.Person.Name) //Create a Shape interface with Area() method r := Rectangle{width: 4, height: 5} fmt.Println("Area of the rectangle is : ", r.Area()) //Print full Name with first name and last name struct name := Name{firstName: "Raju", middleName: "", lastName: "Bhai"} fmt.Println("FullName : ", name.fullName()) // Add a method AgeInYears() to Name fmt.Printf("Age of %v is : %v", name.fullName(), name.AgeInYears()) } type Person struct { Name string Age int } type Employee struct { Person EmployeeID string Department string } type Shape interface { Area() float64 } type Rectangle struct { width float64 height float64 } func (r Rectangle) Area() float64 { return r.width * r.height } var personDetails = map[string]int{"Ram": 23, "Raju": 44, "Sharma": 34} type Name struct { firstName string middleName string lastName string } func (n Name) AgeInYears() int { if age, ok := personDetails[n.firstName]; ok { return age } return -1 } func (n Name) fullName() string { //denoting the fullName function belongs to the Name struct return n.firstName + " " + n.middleName + " " + n.lastName } #Golang #GolangForCoding #StructAndInterfacesInGolang #Examples #Struct #Interfaces Golang Golang Development As you are shifting towards golang from java or python, u may thing that we can use the Same class name and all that here in Golang also we can import the struct from other package and mention that package_name.struct_name If any doubts or any topics to be taken further, you can comment it out or mail me out : surajece2020@gmail.com Feel free to reach out, Happy learning! 😊
To view or add a comment, sign in
-
#java 🟩 Day 47 – Exception Handling + Global Error Response in Spring Boot (HinEnglish, Step-by-Step, #Tech47) आज का लक्ष्य: Backend ko itna smart banana ki error aaye toh system tootey नहीं — balki samjhaaye --- 🔹 Step 1: What is Exception Handling? HinEnglish: Exception handling ka matlab hai unexpected errors ko catch karna aur unka proper response dena — taaki system crash na ho aur user ko meaningful message mile. 🧠 Real-world analogy: > Ek ATM machine jo card error pe quietly message dikhata hai — bina machine hang kiye. ✅ Benefits: - Prevents system crashes - Improves user experience - Helps debugging - Enables centralized error control --- 🔹 Step 2: Types of Exceptions ✅ Checked Exception: Compile-time (e.g., IOException) ✅ Unchecked Exception: Runtime (e.g., NullPointerException) ✅ Custom Exception: Business-specific errors (e.g., UserNotFoundException) --- 🔹 Step 3: Global Exception Handling - Use @ControllerAdvice + @ExceptionHandler - Create centralized class to handle all exceptions - Return structured response with status, message, timestamp 🧠 Example: `java @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) { return new ResponseEntity<>(new ErrorResponse("User not found", LocalDateTime.now()), HttpStatus.NOT_FOUND); } } ` --- 🔹 Step 4: Java Full Stack Integration ✅ Spring Boot: Centralized error handling ✅ React: Show error messages via toast or modal ✅ Postman: Test error responses with invalid inputs ✅ DTOs: Use ErrorResponse class for structured output ✅ GitHub: Push code + README + screenshots ✅ Docker: Deploy with error logs enabled --- 🔹 Step 5: DSA + Tools Relevance ✅ DSA: Try-catch logic = control flow ✅ Tools: - IntelliJ debugger - Spring Boot actuator for error metrics - Logback for structured logging ✅ Monitoring: Use ELK stack or Prometheus for error tracking ✅ Validation: Use @Valid, @NotNull, @Size for input checks --- 🔹 Step 6: Interview Questions - Q1: What is the difference between checked and unchecked exceptions? - Q2: How do you implement global exception handling in Spring Boot? - Q3: What is the role of @ControllerAdvice? - Q4: How do you return custom error responses? - Q5: How do you handle validation errors? --- 🔹 Step 7: Practice Tasks - ✅ Create custom exceptions for UserNotFound, InvalidOrder - ✅ Build GlobalExceptionHandler class - ✅ Create ErrorResponse DTO - ✅ Test with invalid inputs via Postman - ✅ Document logic in Day47_ExceptionHandling/README.md - ✅ Push code, screenshots, and error flow diagram to GitHub --- 🎯 प्रेरणा का संदेश: > “Error handling is not about hiding mistakes — it’s about responding with grace. आज आपने backend ko samajhdar banaya.” JavaFullStack #ExceptionHandling #GlobalErrorResponse #SpringBoot #ReactJS #JavaMastery #Tech47 #GitHubShowcase
To view or add a comment, sign in
-
Today i practiced the loops and conditions In Java we have if, else, if-else, while, for, switch, foreach etc.. In Golang we have if, if else, for, switch that's it, and for sudden recap, i have prepared a short cheat sheet with examples, just a little but of scroll to understand. package main import ( "fmt" "strings" ) func main() { var number1, number2 int var operator string fmt.Scanln(&number1) fmt.Scanln(&number2) fmt.Scanln(&operator) switch operator { case "+": { fmt.Printf("%v : ", number1+number2) } case "-": { fmt.Printf("%v : ", number1-number2) } case "*": { fmt.Printf("%v : ", number1*number2) } case "/": { fmt.Printf("%v : ", number1/number2) } default: fmt.Printf("%v : ", 0) } //even or odd s := 2 if s%2 == 0 { fmt.Println("It is even") } else { fmt.Println("it is odd") } //leap year year := 2020 if (year%4 == 0 && year%100 != 0) || (year%400 == 0) { fmt.Println("it is a leap year") } else { fmt.Println("it is not a leap year") } //max in three numbers a, b, c := 1, 2, 3 if a > b { if a > c { fmt.Printf("%d is largest\n", a) } else { fmt.Printf("%d is largest\n", c) } } else { if b > c { fmt.Printf("%d is largest\n", b) } else { fmt.Printf("%d is largest\n", c) } } //tables of 5 table_number := 5 for i := 1; i <= 10; i++ { fmt.Printf("%d * %d = %d\n", table_number, i, table_number*i) } //Sum of Digits sod := 123 result := 0 for sod > 0 { result += sod % 10 sod = sod / 10 } fmt.Printf("result : %d\n", result) //Reverse a number number := 456 reverse := 0 for number > 0 { reverse = (reverse * 10) + number%10 number = number / 10 } fmt.Printf("the reverse number : %d\n", reverse) // Count vowels in a string vowel_String := "Suraj" vowel_count := 0 for _, ch := range strings.ToLower(vowel_String) { if strings.ContainsRune("aeiou", ch) { vowel_count++ } } fmt.Printf("vowel_count : %d\n", vowel_count) }
To view or add a comment, sign in
-
💡 𝗝𝗮𝘃𝗮 𝟴: 𝗣𝗼𝘄𝗲𝗿 𝗼𝗳 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 One of the biggest milestones in J𝗮𝘃𝗮 𝟴 was the introduction of Lambda Expressions — a way to write clean, expressive, and functional-style code. Before Java 8, we relied heavily on anonymous classes to pass behavior. With Lambdas, we can define the same logic in a single line. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: @𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 𝗶𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 𝗖𝗮𝗹𝗰𝘂𝗹𝗮𝘁𝗼𝗿 { 𝗶𝗻𝘁 𝗼𝗽𝗲𝗿𝗮𝘁𝗲(𝗶𝗻𝘁 𝗮, 𝗶𝗻𝘁 𝗯); } 𝗖𝗮𝗹𝗰𝘂𝗹𝗮𝘁𝗼𝗿 𝗮𝗱𝗱 = (𝗮, 𝗯) -> 𝗮 + 𝗯; 𝗦𝘆𝘀𝘁𝗲𝗺.𝗼𝘂𝘁.𝗽𝗿𝗶𝗻𝘁𝗹𝗻(𝗮𝗱𝗱.𝗼𝗽𝗲𝗿𝗮𝘁𝗲(𝟱, 𝟯)); // 𝟴 𝗟𝗮𝗺𝗯𝗱𝗮𝘀 𝘄𝗼𝗿𝗸 𝘄𝗶𝘁𝗵 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 (𝗼𝗻𝗲 𝗮𝗯𝘀𝘁𝗿𝗮𝗰𝘁 𝗺𝗲𝘁𝗵𝗼𝗱), 𝗲𝗻𝗮𝗯𝗹𝗶𝗻𝗴 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘁𝗼: ✅ Reduce boilerplate ✅ Improve code readability ✅ Write elegant Stream API pipelines ✅ Handle asynchronous logic more easily 𝗥𝗲𝗮𝗹 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲𝘀: Event handling (ActionListener e -> ...) Thread execution (new Thread(() -> ...)) Data filtering with Streams Lambdas represent a shift from object-oriented to functional thinking in Java — bringing flexibility, clarity, and speed to your everyday code. ⚙️ 💼 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 & 𝗔𝗻𝘀𝘄𝗲𝗿𝘀 𝗤𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 𝗶𝗻 𝗝𝗮𝘃𝗮? 👉 A short block of code that can be passed around and executed, used to represent a functional interface. 𝗤𝟮. 𝗖𝗮𝗻 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 𝗯𝗲 𝘂𝘀𝗲𝗱 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗮 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗶𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲? 👉 No. They can only be used with interfaces that have exactly one abstract method. 𝗤𝟯. 𝗔𝗿𝗲 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 𝗼𝗯𝗷𝗲𝗰𝘁𝘀? 👉 No, but at runtime, they are represented as instances of functional interfaces. 𝗤𝟰. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗯𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝘂𝘀𝗶𝗻𝗴 𝗟𝗮𝗺𝗯𝗱𝗮𝘀? 👉 Less boilerplate code, cleaner syntax, improved readability, and easier use of Streams and functional APIs. 𝗤𝟱. 𝗖𝗮𝗻 𝗮 𝗟𝗮𝗺𝗯𝗱𝗮 𝗮𝗰𝗰𝗲𝘀𝘀 𝘃𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗳𝗿𝗼𝗺 𝘁𝗵𝗲 𝗲𝗻𝗰𝗹𝗼𝘀𝗶𝗻𝗴 𝘀𝗰𝗼𝗽𝗲? 👉 Yes, but those variables must be final or effectively final. 𝗤𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗟𝗮𝗺𝗯𝗱𝗮 𝗮𝗻𝗱 𝗔𝗻𝗼𝗻𝘆𝗺𝗼𝘂𝘀 𝗖𝗹𝗮𝘀𝘀? 👉 Lambdas are more concise and don’t create a separate class file at compile time; anonymous classes do. #Java #LambdaExpressions #Java8 #FunctionalProgramming #CleanCode #SoftwareDevelopment #BackendEngineering #JavaDeveloper
To view or add a comment, sign in
-
🧹 What is a Garbage Collector? In Java, the Garbage Collector (GC) automatically manages memory for you. It finds objects that your code no longer uses and frees up that memory. Sounds boring? 😐 Okay — let’s make it interesting! 🚀 💡 G1 Garbage Collector — the Modern Hero Since Java 9, the G1 Garbage Collector has been the default GC in most Java distributions. Why? Because it offers high performance, predictable pause times, and smart memory management — all at once. 🏗️ G1 GC Architecture — the Core Concepts G1 GC is built on a few powerful ideas: Generational Region-based Parallel Mostly Concurrent Stop-the-world (STW) Evacuating Let’s break down what these actually mean (no buzzwords, just clarity 👇). 🧬 Generational G1 follows the weak generational hypothesis — most objects die young. So it divides the heap into two main areas: Young Generation → newly created objects (Eden + Survivor spaces) Old Generation → objects that have survived several GC cycles Example: Person person = new Person(); This person object is created in the Young region. 🧩 Region-Based & Incremental Design Instead of one big contiguous heap, G1 divides memory into many equal-sized regions (1–32 MB each). This allows G1 to collect regions incrementally — reclaiming only parts of the heap that need cleanup, reducing pause times. 🧠 Remembered Sets & Write Barriers To track cross-region references (like when an old object references a young one), G1 uses: Remembered Sets (RSet) → data structures that track which regions reference others Write Barriers → tiny pieces of code the JVM inserts to update RSets when references change ⚙️ Parallel and Concurrent Phases G1 uses multiple threads to perform GC tasks (parallel) and runs some parts concurrently with your application. Advantages: ✅ Reduced pause time ✅ Scales to large heaps Trade-offs: ⚠️ Slightly higher CPU overhead ⚠️ Lower throughput compared to simpler collectors ⏸️ Stop-the-World (STW) Even though G1 is concurrent, some phases (like object evacuation) are stop-the-world events. That means all application threads pause briefly while G1 reclaims memory. The good news: G1 aims to keep those pauses short and predictable, and you can tune them 🚚 Evacuating (Compacting the Heap) G1 reclaims space by moving live objects from one region to another — this is called evacuation. Here’s how: New objects go into Eden. Surviving objects move to Survivor regions. Older survivors eventually move to the Old regions. 🧱 Humongous Objects Larger Objects are allocated in special regions outside the normal young/old flow. G1 handles them carefully — it doesn’t move them often, and only reclaims those regions when no live references remain. 💡 Pro Tip: If you’re getting frequent OutOfMemoryError and your heap contains very large objects (e.g., 17 MB JSON blobs or arrays), You know where to debug. #Java #JVM #GarbageCollection #G1GC #JavaPerformance #MemoryManagement #JavaDeveloper #JavaCore
To view or add a comment, sign in
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Multi-Release JAR" ka hidden feature!🤯 ```java // Java 8 version - base code public class TimeUtils { public static String getTime() { return "Legacy time: " + new Date(); } } // Java 11 version - META-INF/versions/11/TimeUtils.java public class TimeUtils { public static String getTime() { return "Modern time: " + Instant.now(); } } ``` Secret: Ek hi JAR mein multiple Java versions ke liye alag-alag class files ho sakti hain!💀 --- Post 2: Java ka "ConstantDynamic" - invokedynamic for constants!🔥 ```java public class ConstantDynamic { // Java 11+ mein constants bhi dynamically resolve ho sakte hain public static final String DYNAMIC_CONSTANT = ConstantDescs.of("Dynamically resolved constant"); // Bytecode level par invokedynamic use karta hai // instead of constant pool entry! } ``` Internal Magic: · Traditional: Constant Pool → LDC instruction · New: ConstantDynamic → invokedynamic instruction · Dynamic constant resolution at runtime! 💡 --- Post 3: Java ka "Vector API" - SIMD operations ka raaz!🚀 ```java import jdk.incubator.vector.*; public class VectorMagic { public static void main(String[] args) { IntVector a = IntVector.fromArray(IntVector.SPECIES_256, new int[]{1,2,3,4,5,6,7,8}, 0); IntVector b = IntVector.fromArray(IntVector.SPECIES_256, new int[]{8,7,6,5,4,3,2,1}, 0); IntVector result = a.add(b); // ✅ 8 operations ek saath! // CPU level par SIMD instructions use karta hai } } ``` Performance: 10x faster for mathematical operations!💪 --- Post 4: Java ka "Heap Allocation" ka hidden alternative!🔮 ```java import java.lang.foreign.*; public class OffHeapMagic { public static void main(String[] args) { // Heap se bahar memory allocate karo! try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(100); // Direct OS memory access - no GC overhead! segment.set(ValueLayout.JAVA_INT, 0, 42); int value = segment.get(ValueLayout.JAVA_INT, 0); } } } ``` Benefits: · Zero GC pressure · Direct memory access · C-like performance 💀 --- Bhai, yeh features toh aane wali Java generations ke liye hain! 😎
To view or add a comment, sign in
-
💭 Java Memory Leaks: They Exist (Even with Garbage Collection!) 🧠 Most developers believe: > “Java has Garbage Collection, so memory leaks can’t happen.” But here’s the truth 👇 Even with GC, your app can still leak memory — and the scary part? It happens silently. 😬 --- ⚙️ How It Happens GC only removes objects that are no longer referenced. If something still holds a reference — even accidentally — the GC leaves it untouched. Common leak culprits 👇 1️⃣ Static fields — A static list or map that keeps growing and never cleared. 2️⃣ Inner classes / Anonymous classes — Hold an implicit reference to the outer class. 3️⃣ ThreadLocal misuse — Forgetting to call remove() keeps data alive across threads. 4️⃣ Caches that never expire — Especially when using custom in-memory maps. --- 🚨 Real-world example private static List<Data> cache = new ArrayList<>(); public void loadData() { cache.add(new Data()); } Every call keeps adding objects — and since cache is static, the GC can never reclaim that memory 🧱 --- 💡 How to Prevent It ✅ Always clear ThreadLocal after use ✅ Use WeakReference or WeakHashMap for caches ✅ Monitor heap usage with tools like VisualVM or Eclipse MAT ✅ Watch out for static collections or lingering listeners --- ⚡ The Takeaway Garbage Collection isn’t a silver bullet — it’s a helper, not a housekeeper. As engineers, it’s our job to manage references wisely 💪 --- 💬 Your turn: Have you ever faced a production memory issue that GC alone couldn’t fix? 👇 Share your experience — it might help someone else today! #Java #GarbageCollection #MemoryLeak #PerformanceTuning #BackendDevelopment #CleanCode #JavaDeveloper
To view or add a comment, sign in
-
🚀 𝐇𝐨𝐰 𝐈 𝐑𝐞𝐝𝐮𝐜𝐞𝐝 𝐌𝐲 𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝐃𝐨𝐜𝐤𝐞𝐫 𝐈𝐦𝐚𝐠𝐞 𝐒𝐢𝐳𝐞 𝐛𝐲 ~𝟑𝟓𝟎 𝐌𝐁 Recently, I optimized one of my Java Spring Boot Docker images and managed to cut down nearly 350 MB from the final image size. Here’s how I did it 👇 🧱 𝐓𝐡𝐞 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 Most Java base images (like amazoncorretto:17) are JDK-based — full of development-time tools we never need in production: Compiler (javac) Debugger tools Header files Source code Mission Control, javadoc, etc. All these add unnecessary weight and easily bloat the image to 450–500 MB. And after Amazon Corretto 11, AWS stopped publishing standalone JRE images. That means for Java 17+, you’re forced to ship a full JDK even if you only need a runtime. 🔸 Note: Other distributions like Eclipse Temurin (by Adoptium) still provide official JRE builds and Docker images — a great alternative if you want a maintained lightweight runtime base. ⚙️ 𝐓𝐡𝐞 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 👉 Create a custom JRE image using the JDK itself. 1. Start from Corretto JDK 17 (official image). 2. Use jlink (available since JDK 9) to generate a minimal runtime containing only the modules your app actually needs: jlink \ --module-path $JAVA_HOME/jmods \ --add-modules java.base,java.logging,java.sql,java.xml \ --output /custom-jre \ --strip-debug \ --no-man-pages \ --no-header-files \ --compress=2 3. Use that /custom-jre as your runtime in the final Docker image. 4. Apply a multi-stage Docker build so the JDK and build tools never reach your production layer. 📦 𝐓𝐡𝐞 𝐑𝐞𝐬𝐮𝐥𝐭 Image size dropped from ~600 MB → ~250 MB Faster pull/push in CI/CD pipelines Quicker container startup Smaller attack surface 🔗 𝐁𝐨𝐧𝐮𝐬 𝐓𝐢𝐩 If you want a prebuilt runtime, check out: 👉 pnavato/amazoncorretto-jre (unofficial community image) Or use Eclipse Temurin JRE — it’s an official lightweight option from Adoptium that stays updated and secure. Still, building your own custom JRE gives you full control and ensures nothing extra is shipped to production. #Java #SpringBoot #Docker #DevOps #Microservices #CICD #AmazonCorretto #EclipseTemurin #PerformanceOptimization #CloudEngineering
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development