🚀 𝐇𝐨𝐰 𝐈 𝐑𝐞𝐝𝐮𝐜𝐞𝐝 𝐌𝐲 𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝐃𝐨𝐜𝐤𝐞𝐫 𝐈𝐦𝐚𝐠𝐞 𝐒𝐢𝐳𝐞 𝐛𝐲 ~𝟑𝟓𝟎 𝐌𝐁 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
Prathamesh Zore’s Post
More Relevant Posts
-
#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
-
🔰 𝐃𝐚𝐲 𝟗𝟔/𝟏𝟎𝟎 – 𝟏𝟎𝟎 𝐃𝐚𝐲𝐬 𝐨𝐟 𝐉𝐚𝐯𝐚 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 📌 Topic: Java Virtual Machine Tool Interface (JVM TI) 🧩 1. What is JVM TI? The Java Virtual Machine Tool Interface (JVM TI) is a native-level interface that allows developers to build profilers, debuggers, and monitoring tools for Java applications. It interacts directly with the JVM, enabling access to deep runtime details like threads, heap memory, and class loading. In short: > JVM TI = A bridge between the JVM and native agents for debugging and monitoring. ⚙️ ⚙️ 2. What JVM TI Can Do Here’s what you can achieve using JVM TI: ✅ Inspect and control threads and heap memory ✅ Monitor class loading/unloading events ✅ Track garbage collection and object creation ✅ Access local variables, call stacks, and methods ✅ Intercept method entry/exit and exception events It’s mainly used by native agents written in C/C++ to interact with the JVM internals. 🧠 3. JVM TI vs Java Agent (Point-by-Point Comparison) Let’s clearly see how JVM TI differs from a Java Agent 👇 1️⃣ Programming Language: JVM TI → Implemented in C/C++ Java Agent → Implemented in Java 2️⃣ Access Level: JVM TI → Low-level access (closer to the JVM core) Java Agent → High-level access through Java API 3️⃣ Use Case: JVM TI → Used for building profilers, debuggers, and diagnostic tools Java Agent → Used for monitoring, logging, and bytecode instrumentation 4️⃣ Performance Impact: JVM TI → Slightly higher impact due to native calls Java Agent → Lower impact, operates within JVM boundaries 5️⃣ Control Over JVM: JVM TI → Full control, can inspect and modify runtime behavior deeply Java Agent → Limited control, works within managed Java space 6️⃣ Complexity: JVM TI → More complex (requires native programming) Java Agent → Easier to implement using Java’s Instrumentation API 🧭 4. How JVM TI Works The JVM TI agent interacts with the JVM through callbacks. When specific events (like GC, thread start, or method call) occur, the JVM triggers callbacks in your agent code, allowing real-time inspection or action. 🔐 5. Real-World Use Cases 🧰 Common tools built using JVM TI include: Profilers → VisualVM, JProfiler, YourKit Debuggers → IntelliJ, Eclipse Debugger Monitoring Tools → Java Mission Control (JMC) Security Agents → Runtime anomaly detection tools 💡 6. Why It’s Important Understanding JVM TI helps you see how deep tools interact with the JVM internals — it’s the foundation of most advanced performance analyzers and debugging frameworks in the Java ecosystem. 🚀 Final Thought The JVM TI opens the door to the JVM’s internal world 🧠 — allowing developers to build robust tools for performance analysis, debugging, and monitoring. It’s one of the most powerful — yet least known — parts of Java! 💪 #Java #CoreJava #JVM #JVMTI #JavaPerformance #Instrumentation #Profiling #Debugging #AdvancedJava #JavaDeveloper #100DaysOfJava #100DaysOfCode #SoftwareEngineering #JProfiler #VisualVM
To view or add a comment, sign in
-
💭 Heap vs Stack Memory in Java — The Real Difference (Explained Simply) 🧠 You’ve probably heard these terms a hundred times: > “Object is stored in the heap.” “Local variable goes on the stack.” But what does that really mean? 🤔 Let’s break it down 👇 --- 🔹 1️⃣ Stack — The Short-Term Memory The stack stores: Method calls 🧩 Local variables References to objects in the heap It’s fast, organized in LIFO (Last-In, First-Out) order, and automatically cleared when a method ends. Once a method returns, all its stack frames vanish — poof 💨 Example 👇 void test() { int x = 10; // stored in stack String s = "Java"; // reference in stack, object in heap } --- 🔹 2️⃣ Heap — The Long-Term Memory The heap is where all objects live 🏠 It’s shared across threads and managed by the Garbage Collector. It’s slower than the stack — but it’s what makes Java flexible and object-oriented. When you do: Person p = new Person("Tushar"); → p (the reference) lives on the stack, → the actual Person object lives in the heap. --- ⚡ Pro Tip Memory leaks usually happen in the heap, while StackOverflowError (yes, the real one 😅) comes from — you guessed it — an overfilled stack due to deep recursion or infinite method calls. --- 💬 Your Turn Do you monitor heap and stack usage in your apps (via tools like VisualVM or JConsole)? 👇 Or do you just “trust the JVM”? #Java #MemoryManagement #JVM #GarbageCollection #BackendDevelopment #CleanCode #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
☕ JVM Architecture — Behind the Scenes of Every Java Program The Java Virtual Machine (JVM) is the heart of Java — it enables platform independence by running bytecode on any system. It performs 3 key functions: 1️⃣ Loads Java bytecode (.class files) 2️⃣ Verifies and prepares memory for classes 3️⃣ Executes the program 🧩 JVM Major Components JVM ├── Class Loader Subsystem ├── Runtime Data Areas └── Execution Engine ├── Interpreter ├── JIT Compiler ├── Garbage Collector ├── Native Interface (JNI) └── Native Method Libraries 🔹 1. Class Loader Subsystem It’s the first component of the JVM, responsible for loading .class files into the JVM’s Runtime Data Areas, which reside inside the JVM process in the primary memory (RAM). Responsibilities: Loading → Linking → Initialization ✅ Loading: Loads class bytecode from disk, JARs, or remote sources using: Bootstrap ClassLoader → Core Java (<JAVA_HOME>/lib) Extension ClassLoader → Optional libs (lib/ext) Application ClassLoader → User-defined classes from classpath ✅ Linking: Verifies bytecode (security + correctness), prepares memory for static variables, and assigns default values. ✅ Initialization: Assigns actual values to statics and executes static blocks. At this stage, the class is ready for use. ☕ Java 8 vs Java 11 – Behind the Scenes Java 8 (Traditional Way) 1️⃣ Save Hello.java on disk (secondary memory) 2️⃣ Run javac Hello.java → generates Hello.class on disk 3️⃣ Run java Hello → Class Loader loads .class from disk → JVM executes it ✅ .class file exists on disk Java 11 (Single-File Execution) 1️⃣ Save Hello.java 2️⃣ Run java Hello.java → JVM compiles it internally 3️⃣ Bytecode (.class) generated temporarily in RAM 4️⃣ Class Loader loads in-memory bytecode into Method Area 5️⃣ After execution → bytecode discarded ✅ .class file lives only in memory 🧠 2. Runtime Data Areas Memory areas inside the JVM where program data lives during execution. RAM (Primary Memory) └── JVM Process ├── Method Area → class info, static vars, bytecode ├── Heap → objects ├── Stack → Method calls, local variables, references ├── PC Register → next instruction pointer └── Native Method Stack → JNI/native calls ⚙️ 3. Execution Engine Once classes are loaded into the Method Area, the Execution Engine translates bytecode into native machine code and then the CPU runs that native code. Components: * Interpreter → Reads bytecode line by line (slower) * JIT Compiler → Converts hot spots to native code for speed * Garbage Collector → Reclaims unused memory from the Heap JNI & Native Libraries: * JNI (Java Native Interface): Allows Java to call C/C++ methods. * Native Method Libraries: Actual libraries (.dll, .so) used by JNI. ☕ Loved it? Drop a coffee — let’s keep the Java vibes strong! 💻 #Java #JVM #JavaDeveloper #JVMArchitecture #CoreJava #Programming #Developers #SoftwareEngineering #JavaCommunity #TechLearning #BackendDevelopment #LearnJava #CodeWithMohan
To view or add a comment, sign in
-
🌐 Day 14 — Dynamic URLs, Path Variables & Query Parameters in Spring Boot Continuing my 100 Days of Java Backend, Spring Boot & AI Integration journey 🚀 Today, I explored how to make APIs dynamic and flexible using Path Variables, Query Parameters, and Request Headers in Spring Boot. Even though I already knew these concepts, revisiting them gave me a deeper understanding of how real-world APIs handle client input dynamically 💡 ------------------------------------------------------------------------------- 💡 What I Learned 🔗 Dynamic URLs with Path Variables (@PathVariable) Learned how to capture data directly from the URL — for example, /users/{id} — and map it to method parameters in the controller. 🔍 Query Parameters using @RequestParam Explored how to filter, sort, and search data using parameters like /products?category=electronics&price=500. 🧩 Handling Multiple Query Parameters Understood how Spring automatically binds multiple query parameters and how to make some of them optional. 📬 Using @RequestHeader Annotation Learned how to extract information from HTTP headers, such as authentication tokens or client metadata. ⚙️ Combining All — PathVariable + RequestParam + RequestHeader Built APIs that use all three together, simulating real-world backend operations where client, server, and request metadata all interact. ------------------------------------------------------------------------------- This day reinforced how Spring Boot empowers developers to design robust and interactive APIs that adapt to real-world use cases 💪 Next, I’ll dive deeper into database connectivity and JPA integration — where APIs meet persistent data 🔗 #100DaysOfJavaBackend #Day14 #SpringBoot #RESTAPI #JavaDeveloper #PathVariable #RequestParam #RequestHeader #BackendDevelopment #LearningJourney #SpringFramework #SoftwareEngineering #CleanCode #AIDeveloper
To view or add a comment, sign in
-
🚀 JVM Architecture in 2025: What Every Java Developer Should Know The Java Virtual Machine (JVM) has quietly evolved into one of the most sophisticated runtime environments in modern software engineering. With Java 25, the JVM is faster, smarter, and more scalable than ever — and understanding its architecture can seriously level up how you write, debug, and tune Java code. 🔹 1. Class Loader Subsystem Loads .class files into memory using a layered delegation model: Bootstrap Loader – Loads core Java classes (java.base) from the module system. Platform Loader – Loads platform modules (like java.logging, java.sql) – modular since Java 9. Application Loader – Loads application-specific classes from the classpath/module path. Custom Loaders – Frameworks like Spring, Quarkus, and containers use these for dynamic class loading. 👉 In Java 25, the module system (jlink, jmod) and sealed types mean more control over what’s visible and loaded. 🧠 2. Runtime Data Areas Where your application lives during execution: Heap – Shared memory for objects. Modern collectors like ZGC and Shenandoah offer near-pause-less GC even at massive scales. Method Area – Holds class metadata, now part of Metaspace (off-heap since Java 8). Stacks – Each thread (including virtual threads in Java 21+) gets its own stack for method calls and local variables. PC Register – Keeps track of the current bytecode instruction per thread. Native Method Stack – Supports calls to native (non-Java) code via JNI. 🔍 Java 25+ virtual threads (Project Loom) are radically efficient because they require far less stack memory. ⚙️ 3. Execution Engine Turns bytecode into real execution: Interpreter – Quick to start, reads bytecode one instruction at a time. JIT Compiler – Just-in-time compiles hot methods to native machine code using C2 and Graal. GC Engine – Modern collectors like ZGC offer ultra-low pause times, and adaptive memory regions. 💡 JVMs now self-tune aggressively using runtime profiling and tiered compilation strategies. 🌉 4. Native Interface (JNI) & Foreign Function Support JNI – Traditional way to call C/C++ code (still widely used). Project Panama (Java 22+) – Introduced the Foreign Function & Memory API, making native interop easier, faster, and safer — no more verbose JNI boilerplate. 🌐 JVM in 2025: Modern Capabilities ✅ Virtual threads: Lightweight concurrency, ideal for millions of parallel tasks. ✅ Record classes & sealed hierarchies: Better modeling with strong typing and compiler safety. ✅ Pattern matching: Cleaner, more expressive instanceof, switch, and deconstruction logic. ✅ Improved startup & native images: With tools like GraalVM and jlink, you can generate lean, fast-starting runtimes. #Java25 #JVM #VirtualThreads #JavaInternals
To view or add a comment, sign in
-
#java Day 61 – Java Multithreading Mastery (ExecutorService + Future + CompletableFuture) Goal: Backend ko parallel, scalable aur efficient banana. --- 🔹 Core Concepts - Multithreading: Multiple tasks ek saath run karna → fast response. - ExecutorService: Thread pool manage karta hai, manual thread creation avoid hota hai. - Future: Async computation ka result. - CompletableFuture: Advanced async pipelines with chaining + non-blocking execution. 🧠 Analogy: Ek kitchen jahan ek chef vs multiple chefs ek saath dishes bana rahe hain. --- 🔹 Code Demos ExecutorService `java ExecutorService pool = Executors.newFixedThreadPool(3); Runnable task = () -> System.out.println("Task by: " + Thread.currentThread().getName()); for (int i = 0; i < 5; i++) pool.submit(task); pool.shutdown(); ` Future `java Future<Integer> future = pool.submit(() -> { Thread.sleep(2000); return 42; }); System.out.println("Result: " + future.get()); ` CompletableFuture `java CompletableFuture.supplyAsync(() -> "Hello") .thenApply(msg -> msg + " World") .thenAccept(System.out::println); ` --- 🔹 Real-World Integration - Spring Boot: @Async + Executor config for async services. - React: Parallel API calls for faster UI. - Docker: Multiple backend containers handle concurrent requests. - Monitoring: JConsole, VisualVM, Prometheus. --- 🔹 Interview Prep - Thread vs Runnable vs Callable? - Why ExecutorService > manual threads? - How CompletableFuture improves async pipelines? - What is race condition & deadlock? --- 🔹 Practice Tasks - Create 10 tasks with ExecutorService. - Async factorial with Future. - Pipeline chaining with CompletableFuture. - Explore thenCombine() and thenCompose(). - Push code + results to GitHub. --- 🎯 Motivation: “Concurrency is not chaos — it’s controlled speed. Aaj aapne backend ko enterprise-ready banaya.” #Multithreading #ExecutorService #Future #CompletableFuture #Docker #Concurrency #BackendArchitecture #InterviewPrep #GitHubShowcase #StructuredLearning #LegacyDriven #Tech61
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝟮𝟱: 𝗝𝗮𝘃𝗮 𝗙𝗹𝗶𝗴𝗵𝘁 𝗥𝗲𝗰𝗼𝗿𝗱𝗲𝗿 (𝗝𝗙𝗥) - 𝗝𝗘𝗣 𝟰𝟳𝟯 𝗣𝗿𝗼𝗺𝗲𝘁𝗵𝗲𝘂𝘀 𝗘𝗻𝗱𝗽𝗼𝗶𝗻𝘁 - 𝗣𝗮𝗿𝘁 𝟮 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
To view or add a comment, sign in
-
🚀 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
-
-
Callable, Future, and Thread Pools in Java Explained Simply ExecutorService becomes powerful when you start using Callable and Future. They let you run tasks in the background and get results when ready. Runnable vs Callable Runnable runs a task but returns nothing. Callable runs a task and returns a value. Example: ExecutorService executor = Executors.newFixedThreadPool(3); Callable<Integer> task = () -> { System.out.println("Running in " + Thread.currentThread().getName()); return 5 * 2; }; Future<Integer> result = executor.submit(task); System.out.println("Result: " + result.get()); executor.shutdown(); Output: Running in pool-1-thread-1 Result: 10 Future.get() waits until the result is ready. Why use Callable and Future You can get return values from background tasks. You can handle timeouts with get(timeout, TimeUnit.SECONDS). You can check if a task is done using isDone(). Thread Pools simplify everything ExecutorService pool = Executors.newFixedThreadPool(4); Controls how many threads run at once. Reuses threads to save memory. Perfect for web requests, DB operations, or scheduled jobs. Best practices Always shut down the executor (shutdown() or shutdownNow()). Don’t block the main thread unnecessarily. Use fixed pools for predictable workloads. ExecutorService + Callable + Future = powerful, efficient concurrency. What kind of background tasks do you usually handle in your backend systems? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
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