👋 Hello there! Welcome to our Java Concurrency Series! 🚀
🚀 In this series, we'll dive into various aspects of Java concurrency, from basic to advanced topics. We'll begin by tackling fundamental concepts such as thread caching issues, basic thread synchronization, and utilizing multiple locks using synchronized code blocks. Stay tuned for an insightful journey into the world of multithreading!
Table of Contents
- 🔄 Understanding Concurrency
- 🧵What are Threads
- 💾Problem with Thread Caching
- 🔒 Solution: Volatile Keyword
- 🏎️ Problem: Race Conditions
- 🛠️ Solution: Synchronized Keyword
- 🧱 Synchronize Code Blocks
- 🔐 Locking
🔄 Understanding Concurrency
Concurrency is where your computer can handle multiple tasks simultaneously. It involves managing the execution of multiple tasks concurrently to improve performance and responsiveness in software applications.
🧵 What are Threads
Thread is like a separate path of execution within a program. When a program is running, it can have multiple threads running concurrently, each performing its own set of instructions independently.
💾 Problem with Thread Caching
In the code below, we create the Clock class as a Runnable and run it by spawning a new Thread from the main class. Once started, the Clock class's run method will keep running the while loop. To stop this, we need to call the cancel method from the main thread, which will:
- Change the
isStoppedvalue to false. - Write it in the memory.
However, the thread running the while loop may not have the updated value of isStopped and could still have a local cache of the old value of isStopped (false).
public class Main {
public static void main(String[] args) throws InterruptedException {
Clock clock = new Clock();
Thread thread = new Thread(clock);
thread.start();
Thread.sleep(10000);
clock.cancel();
}
}
class Clock implements Runnable {
private volatile boolean isStopped = false;
public void cancel() {
this.isStopped = true;
}
public void run() {
while (!this.isStopped) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Tick");
}
}
}
🔒 Solution: Volatile Keyword
The values of the volatile variable will never be cached, and all writes and reads will be done to and from the main memory. So, the above thread running the while loop will always have the latest read value from the memory.
Look at the increment method:
- First, we store the value of the counter to local variable
i. - Then, we increment
iby 1. - Finally, we write
iback tocounter.
And two threads are doing this simultaneously.
For example, consider a Counter class where each thread increments a shared counter variable. In this class, the increment() method is declared as synchronized, which means only one thread can execute it at a time for a given Counter object. When a thread calls the increment() method, it automatically acquires the intrinsic lock associated with that method's object, ensuring that no other thread can modify the counter concurrently. Once the method completes its execution, the lock is released, allowing other threads to call the method.
🌟 Thank you for joining us on this Java Concurrency Series journey! 🚀 We'll delve into CountdownLatch, Callable, Futures, and Semaphores soon.
📢 We'd love your feedback to improve our content. Share your thoughts with us!
🤝 Stay connected, happy coding! 🌟
SOCIAL SHARE CARD GENERATOR