Day 7/60 – Backend Development Journey (Multithreading & Synchronization) Today I worked on Java Multithreading and understood how concurrent execution works along with synchronization. What I built Task 1: Parallel Execution: Created two threads to print numbers: • Thread 1 → prints 1 to 5 • Thread 2 → prints 6 to 10 Both run simultaneously using Runnable Task 2: Shared Counter with Synchronization: • Two threads increment a shared counter • Ensured correct final value using locking mechanism Key Concepts Applied 1. Multithreading Running multiple threads in parallel to improve performance. Example 1: • Thread A → handles API requests • Thread B → processes background tasks Example 2: • Thread 1 → file download • Thread 2 → UI updates 2. Race Condition Multiple threads accessing shared data can cause incorrect results. Example 1: • Two threads incrementing the same variable → wrong count Example 2: • Bank balance updates → inconsistent values 3. Synchronization & Locking • Used ReentrantLock to ensure only one thread updates the counter at a time. 4. Thread Coordination • Used join() to wait for threads to finish before printing result. #Java #Multithreading #Concurrency #Threading #Synchronization
Java Multithreading and Synchronization Basics
More Relevant Posts
-
☕ Ever Wondered How JVM Actually Works? Let’s Break It Down. 🚀 Many Java developers use JVM daily, but few truly understand what happens behind the scenes. Let’s simplify it 👇 🔹 Step 1: Write Java Code Create your file like Hello.java 🔹 Step 2: Compile the Code Use javac Hello.java This converts source code into bytecode (.class) 🔹 Step 3: Class Loader Starts Work JVM loads required classes into memory when needed. 🔹 Step 4: Memory Areas Created JVM manages different memory sections: ✔ Heap (objects) ✔ Stack (method calls) ✔ Method Area (class metadata) ✔ PC Register 🔹 Step 5: Execution Engine Runs Code Bytecode is executed using: ✔ Interpreter ✔ JIT Compiler (improves speed) 🔹 Step 6: Garbage Collector Cleans Memory Unused objects are removed automatically. 🔹 Simple Flow Java Code → Bytecode → JVM → Machine Execution 💡 Strong Java developers don’t just write code. They understand what happens under the hood. 🚀 Master fundamentals, and performance tuning becomes easier. #Java #JVM #Programming #SoftwareEngineering #BackendDevelopment #Developers #Coding #JavaDeveloper #TechLearning #SpringBoot
To view or add a comment, sign in
-
-
While building a recent Spring Boot application, I realized... The Hook: Stop defaulting to .parallelStream() to make your Java code "faster." 🛑 The Insight: It’s a common misconception that parallel streams always improve performance. Under the hood, parallelStream() uses the common ForkJoinPool. If you are executing CPU-intensive tasks on a massive dataset, it’s great. But if you are doing I/O operations (like database calls or network requests) inside that stream, you will exhaust the thread pool and bottleneck your entire application. The Pro Tip: Always benchmark. For I/O bound tasks, look into asynchronous programming (like CompletableFuture) or Java 21's Virtual Threads instead of parallel streams. #Java #PerformanceOptimization #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Still confused about how Java actually runs your code? 🤔 Here’s a simple breakdown of how the JVM works 👇 👉 1. Build Phase ✔️ Java code (.java) is compiled using javac ✔️ Converted into bytecode (.class files) 👉 2. Class Loading ✔️ JVM loads classes using: Bootstrap Class Loader Platform Class Loader System Class Loader 👉 3. Linking ✔️ Verify → Prepare → Resolve ✔️ Ensures code is safe and ready to run 👉 4. Initialization ✔️ Static variables & blocks are initialized 👉 5. Runtime Data Areas ✔️ Method Area & Heap (shared) ✔️ Stack, PC Register, Native Stack (per thread) 👉 6. Execution Engine ✔️ Interpreter executes bytecode line by line ✔️ JIT Compiler converts hot code into machine code for speed 👉 7. Native Interface (JNI) ✔️ Interacts with native libraries when needed 💡 JVM is the reason behind Java’s “Write Once, Run Anywhere” power. 📌 Save this post 🔁 Repost to help others 👨💻 Follow Abhishek Sharma for more such content #Java #JVM #SystemDesign #BackendDevelopment #SoftwareEngineer #Developers #TechJobs #Programming #LearnJava
To view or add a comment, sign in
-
-
📒 Day 30 — Hide what is unnecessary, show what matters, that is Abstraction!⚡Java keeps pushing me to think smarter every single day! 💪 Today I explored another fundamental principle of Object-Oriented Programming, Abstraction. ➠ What is Abstraction? At its core, Abstraction is the practice of exposing only the essential features of an object while hiding internal implementation. It shifts the focus from HOW something works to WHAT it does. 👉In Java, Abstraction is implemented through two powerful mechanisms: ➠ Abstract Classes: Declared using the `abstract` keyword, these classes serve as a blueprint, allowing a mix of defined and undefined methods to guide subclass behavior. ➠ Interfaces: To achieve 100% Abstraction in Java we use Interfaces — stay tuned for Day 31! 🚀 💡 Real-World Perspective: Consider an ATM machine. As a user, you simply insert your card and withdraw cash — you have no visibility into the complex banking logic running behind the scenes. That seamless experience is Abstraction at work. 🔑 Why Abstraction Matters: • Simplifies complex system design • Promotes code reusability and modularity • Strengthens maintainability across teams • Establishes clear contracts between components Mastering Abstraction is a critical step toward writing clean, professional, and enterprise-grade Java applications. If you are also on a learning journey — drop a 🔥 in the comments! Day 31 awaits — the journey continues!🔥 #Java #100DaysOfCode #OOP #LearningInPublic #JavaDeveloper #Abstraction #SoftwareEngineering #Coding #DevCommunity
To view or add a comment, sign in
-
A lot of Java devs solve thread-safety issues with one keyword: synchronized. And honestly, sometimes that’s the right call. Simple, readable, gets the job done. But I’ve seen codebases where synchronized is used everywhere, and once traffic grows, performance starts falling apart. What happens? Only one thread can enter that block/method at a time. If 50 requests hit it together: 1 executes 49 wait So even if your app server has resources, requests are still lining up behind one lock. Where it gets ugly When slow work is inside the lock: -DB queries -External API calls -File operations -Heavy loops / processing Now threads aren’t waiting for CPU. They’re waiting because one thread is holding a lock during slow operations. That’s where response times spike. Better approach depends on the case Use ReentrantLock if you need more control: -tryLock() -timeout -fairness -interruptible waits Use concurrent collections like ConcurrentHashMap instead of manually synchronizing shared maps/lists. Don’t lock the whole method if only one small state update needs protection. Use AtomicInteger / AtomicLong for counters instead of full locks. Real takeaway Thread safety matters. But making everything synchronized is not a concurrency strategy. First make it correct. Then make it scale. #Java #Concurrency #Multithreading #BackendDevelopment #Performance #SoftwareEngineering
To view or add a comment, sign in
-
Java is going back to blocking code. And somehow… getting faster. For years, we were told that scalability required reactive programming. Complex pipelines. Async flows. Non-blocking everything. Then Project Loom arrived. With Virtual Threads in Java 21, the game changed: • Threads are no longer expensive • You can handle millions of concurrent requests • Blocking is no longer a bottleneck And the best part? You can write simple, readable, synchronous code again. With Spring Boot supporting Virtual Threads, we’re seeing a shift: Teams are moving away from reactive complexity Back to a model developers actually enjoy working with Same code style. Better scalability. Less operational complexity. This is not just an improvement. It’s a paradigm shift. Blocking is not the enemy anymore. Bad architecture is. #Java #SpringBoot #VirtualThreads #ProjectLoom #Backend #SoftwareArchitecture #Microservices #Java21 #SoftwareEngineer
To view or add a comment, sign in
-
-
#Post11 In the previous post(https://lnkd.in/dynAvNrN), we saw how to create threads in Java. Now let’s talk about a problem. If creating threads is so simple… why don’t we just create a new thread every time we need one? Let’s say we are building a backend system. For every incoming request/task, we create a new thread: new Thread(() -> { // process request }).start(); This looks simple. But this approach breaks very quickly in real systems because of below mentioned problems. Problem 1: Thread creation is expensive Creating a thread is not just creating an object. It involves: • Allocating memory (stack) • Registering with OS • Scheduling overhead Creating thousands of threads = performance degradation Problem 2: Too many threads → too much context switching We already saw this earlier(https://lnkd.in/dYG3v-vb). More threads does NOT mean more performance. Instead: • CPU spends more time switching • Less time doing actual work Problem 3: No control over thread lifecycle When you create threads manually: • No limit on number of threads • No reuse • Hard to manage failures This quickly becomes difficult to manage as the system grows. So what’s the solution? Instead of creating threads manually: we use something called the Executor Framework. In simple words consider the framework to be like: Earlier, we were manually hiring a worker (thread) for every task. With Executor, we have a team of workers (thread pool), and we just assign tasks to them. Key idea Instead of: Creating a new thread for every task We do: Submit tasks to a pool of reusable threads This is exactly what Java provides using: Executor Framework Key takeaway Manual thread creation works for learning, but does not scale in real-world systems. Thread pools help: • Control number of threads • Reduce overhead • Improve performance We no longer manage threads directly — we delegate that responsibility to the Executor Framework. In the next post, we’ll see how Executor Framework works and how to use it in Java. #Java #Multithreading #Concurrency #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
Continuing my recent posts on JVM internals and performance, today I’m sharing a look at Java 21 Virtual Threads (from Project Loom). For a long time, Java handled concurrency using platform threads (OS threads)—which are powerful but expensive, especially for I/O-heavy applications. This led to complex patterns like thread pools, async programming, and reactive frameworks to achieve scalability. With Virtual Threads, Java introduces a lightweight threading model where thousands (even millions) of threads can be managed efficiently. 👉 When a virtual thread performs a blocking I/O operation, the underlying carrier (platform) thread is released to do other work. This brings Java closer to the efficiency of event-loop models (like in Node.js), while still allowing developers to write simple, synchronous code without callback-heavy complexity. However, in real-world scenarios, especially when teams migrate from Java 8/11 to Java 21, it’s important to keep a few things in mind: • Virtual Threads are not a silver bullet—they primarily improve I/O-bound workloads, not CPU-bound ones • If the architecture is not aligned, you may not see significant latency improvements • Legacy codebases often contain synchronized blocks or locking, which can lead to thread pinning and reduce the benefits of Virtual Threads Project Loom took years to evolve because it required deep changes to the JVM, scheduling, and thread management—while preserving backward compatibility and Java’s simplicity. Sharing a diagram that illustrates: • Platform threads vs Virtual Threads • Carrier thread behavior • Pinning scenarios Curious to hear—are you exploring Virtual Threads in your applications, or still evaluating? 👇 #Java #Java21 #VirtualThreads #ProjectLoom #Concurrency #Performance #SoftwareEngineering
To view or add a comment, sign in
-
-
Most backend bugs in production aren't caused by bad code. They arise from assumptions that were never questioned during development. Common assumptions include: - "This API will always return data." - "The network will always be stable." - "No one will hit this endpoint 1000 times a minute." Defensive programming isn't pessimism; it's simply experience wearing a helmet. #BackendDevelopment #SoftwareEngineering #Java #LessonsLearned
To view or add a comment, sign in
-
🔥 Day 12: forEach vs Stream vs Parallel Stream (Java) Another important concept for writing clean and efficient Java code 👇 🔹 1. forEach (Traditional / External Iteration) 👉 Definition: Iterates over elements one by one using loops or forEach(). ✔ Simple and easy to use ✔ Full control over iteration ✔ Runs in a single thread 🔹 2. Stream (Sequential Stream) 👉 Definition: Processes data in a pipeline (functional style) sequentially. ✔ Cleaner and more readable code ✔ Supports operations like filter(), map() ✔ Runs in a single thread 🔹 3. Parallel Stream 👉 Definition: Processes data using multiple threads simultaneously. ✔ Faster for large datasets ⚡ ✔ Uses multi-core processors ✔ Order may not be guaranteed ❗ 🔹 When to Use? ✔ forEach → simple iteration & full control ✔ Stream → clean transformations & readability ✔ Parallel Stream → large data + performance needs 💡 Pro Tip: Parallel streams are powerful — but use them carefully. Not every task benefits from parallelism. 📌 Final Thought: "Write simple with forEach, clean with Stream, fast with Parallel Stream." #Java #Streams #ParallelStream #forEach #Programming #JavaDeveloper #Coding #InterviewPrep #Day12
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