Concurrency and Multithreading: Doing Things Simultaneously
9 min read
Welcome, fellow Java developer! Ever felt like your program is a bit like a person trying to do a million things at once, but they can only do one thing at a time? It reads a file, then updates the user interface, then makes a network call, and while it's waiting for the network, the entire application just... freezes. 🥶 Frustrating, right?
This is where the magic of Concurrency and Multithreading comes in. It's the art of making your program do multiple things at the same time, leading to more responsive, efficient, and powerful applications.
1. Threads and Runnables: Creating Concurrent Tasks 🧵
The Problem: By default, a Java application runs in a single flow of execution called the main thread. If this thread is busy with a long-running task (like downloading a large file), your application becomes unresponsive.
The Solution: We can create additional threads to handle these long-running tasks in the background, keeping our main thread free to handle user interactions.
In Java, there are two primary ways to create a thread:
a) Implementing the Runnable Interface (Preferred Method)
This is the most common and flexible approach in the industry. You create a class that implements the Runnable interface, which has a single method: run(). The code inside run() is what will be executed in the new thread.
Why is it preferred?
- Flexibility: Your class can still extend another class, as Java doesn't support multiple inheritance of classes.
- Separation of Concerns: It cleanly separates the task to be performed (
Runnable) from the execution mechanism (Thread).
Example:
class DownloadTask implements Runnable {
private String fileName;
public DownloadTask(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
System.out.println("Downloading " + fileName);
// Simulate a long download process
try {
Thread.sleep(3000); // Sleep for 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(fileName + " downloaded!");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main thread started.");
// Create a Runnable task
Runnable task = new DownloadTask("some-file.zip");
// Create a Thread and pass the task to it
Thread downloadThread = new Thread(task);
// Start the new thread
downloadThread.start();
System.out.println("Main thread continues to run...");
}
}b) Extending the Thread Class
You can also create a thread by extending the Thread class and overriding its run() method.
Example:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("This code is running in a separate thread.");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}Fun Fact: The term "thread" in computing was inspired by the "thread of thought" concept, representing a single line of reasoning or execution.
2. Synchronization and Thread Safety: Preventing Data Races 🏁
The Problem: When multiple threads access and modify the same data concurrently, it can lead to a chaotic situation called a race condition. This can result in corrupted data and unpredictable behavior. A specific type of race condition is a data race, which occurs when at least two threads access a shared variable, at least one access is a write, and the accesses are not ordered by a happens-before relationship.
Real-world simulation: Imagine two people trying to withdraw money from the same joint bank account at the exact same moment from two different ATMs. If the system isn't careful, they might both read the initial balance, both withdraw money, and the final balance will be incorrect because one transaction overwrites the other.
The Solution: We need to ensure thread safety, which means our code behaves correctly even when accessed by multiple threads. This is achieved through synchronization, which ensures that only one thread can execute a critical section of code at a time.
The synchronized Keyword
Java provides the synchronized keyword as a simple way to achieve synchronization. It can be applied to methods or blocks of code.
Synchronized Methods: When a method is declared as
synchronized, a thread must acquire a lock on the object instance before it can execute the method. This prevents other threads from executing any synchronized method on the same object instance simultaneously.Synchronized Blocks: This provides more granular control by only locking a specific part of a method, which can be more efficient.
Example (Non-thread-safe vs. Thread-safe):
Without Synchronization (Prone to data races):
class Counter {
private int count = 0;
public void increment() {
count++; // This is not an atomic operation
}
public int getCount() {
return count;
}
}If two threads call increment() at the same time, they might both read the same value of count, both increment it, and then both write back the same new value, losing one of the increments.
With Synchronization:
class SafeCounter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++;
}
// Also synchronized to ensure visibility of the change
public synchronized int getCount() {
return count;
}
}Now, only one thread can be inside the increment() or getCount() method for a given SafeCounter instance at any time, preventing data corruption.
3. The Concurrency API: Thread Pools and Executors 🏊
The Problem: Creating a new Thread for every single task is inefficient. There's a significant overhead in creating and destroying threads. Imagine a busy restaurant hiring a new waiter for every single customer and then immediately firing them after they take the order. It would be chaos and incredibly wasteful!
The Solution: The java.util.concurrent package provides a high-level API to manage threads more efficiently. The core of this is the Executor Framework, which decouples task submission from the mechanics of how each task will be run. We can use a thread pool, which is a collection of pre-instantiated, reusable worker threads.
ExecutorService
The ExecutorService is an interface that represents a thread pool. We can submit Runnable tasks to it, and the service will manage their execution.
The Executors utility class provides factory methods to create different types of thread pools:
Executors.newFixedThreadPool(int nThreads): Creates a thread pool with a fixed number of threads. If all threads are busy, new tasks are placed in a queue to wait. This is great for predictable workloads.Executors.newCachedThreadPool(): Creates a thread pool that can grow dynamically. It reuses existing threads if available; otherwise, it creates a new one. Threads that are idle for 60 seconds are terminated. This is suitable for a large number of short-lived tasks.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
// Create a fixed thread pool with 3 worker threads
ExecutorService executor = Executors.newFixedThreadPool(3);
// Submit 10 tasks for execution
for (int i = 1; i <= 10; i++) {
Runnable task = new WorkerTask("Task " + i);
executor.execute(task);
}
// It's crucial to shut down the executor when you're done
executor.shutdown();
System.out.println("All tasks submitted.");
}
}
class WorkerTask implements Runnable {
private String name;
public WorkerTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " starting: " + name);
try {
Thread.sleep(2000); // Simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished: " + name);
}
}Running this code, you'll see that only 3 tasks start at a time, because our pool size is 3. As tasks finish, the threads pick up new tasks from the queue.
4. CompletableFuture: Modern Asynchronous Programming ⛓️
The Problem: Traditional Future objects (which you can get from an ExecutorService) are a bit basic. They represent a result that will be available in the future, but getting that result with future.get() is a blocking operation. Your code just waits, unable to do anything else. Also, what if you want to do something with the result as soon as it's ready, or combine the results of two different asynchronous tasks? This can lead to complex and messy code, often called "callback hell."
The Solution: Java 8 introduced CompletableFuture, a much more powerful and flexible way to write non-blocking, asynchronous code. It's like giving a barista your order and a pager. You don't have to stand there and stare at them; you can go find a seat and do other things. The pager will buzz when your coffee is ready.
CompletableFuture allows you to chain operations together in a fluent, readable way.
Key Methods:
supplyAsync(Supplier<U> supplier): Executes a task asynchronously that returns a result.thenApply(Function<? super T,? extends U> fn): Takes the result of the previous stage and applies a function to it, returning a newCompletableFuturewith the transformed result.thenAccept(Consumer<? super T> action): Takes the result and performs an action with it. It doesn't return anything.thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn): Combines the result of thisCompletableFuturewith another one.
Example:
Imagine you need to fetch user data from one service and their recent orders from another, and then combine them.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompletableFutureDemo {
public static CompletableFuture<String> getUserDetails() {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Fetching user details...");
sleep(2); // Simulate network latency
return "User: John Doe";
});
}
public static CompletableFuture<String> getRecentOrders() {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Fetching recent orders...");
sleep(3); // Simulate network latency
return "Orders: [Pizza, Soda]";
});
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
CompletableFuture<String> combinedFuture = getUserDetails().thenCombine(getRecentOrders(), (userDetails, orders) -> {
return userDetails + "\n" + orders;
});
// This is a non-blocking way to use the final result
combinedFuture.thenAccept(result -> {
System.out.println("--- Combined Result ---");
System.out.println(result);
});
System.out.println("Main thread is not blocked and can do other things.");
// Wait for the async operations to complete for this demo
sleep(5);
long endTime = System.currentTimeMillis();
System.out.println("Total time: " + (endTime - startTime) + "ms");
}
private static void sleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}Notice how both "Fetching..." messages appear almost immediately. The tasks run in parallel, and the total time taken is roughly the duration of the longest task (3 seconds), not the sum of both (5 seconds). This is the power of non-blocking, asynchronous programming!
📚 References for Extra Reading
- Official Java Documentation:
- Guides and Tutorials:
- Baeldung: Guide To CompletableFuture
- Jenkov.com: Java Synchronized Blocks
- DigitalOcean: Java Thread Pool
Challenge
You are tasked with building a high-performance order processing system. For each order, you need to fetch payment details and shipping information. These two operations are independent and can be performed concurrently to speed up the process.
Your goal is to implement the processOrders method within the OrderProcessor class.
Requirements:
- Create a fixed-size thread pool with 5 threads using an
ExecutorService. This pool must be used for all asynchronous operations. - For each
orderIdin the input list, you must asynchronously and concurrently fetch its payment details (using the providedfetchPaymentDetailsmethod) and shipping information (usingfetchShippingInfo). - Once both pieces of information are available for a single order, combine them into a
ProcessedOrderobject. Thesummaryfield of theProcessedOrdershould be formatted as:"Order [orderId]: Payment=[paymentDetails], Shipping=[shippingInfo]". - The
processOrdersmethod must return aListofCompletableFuture<ProcessedOrder>, where eachCompletableFuturerepresents the ongoing processing of a single order. - Ensure you properly shut down the
ExecutorServicebefore the method returns.
Expected result
Your implemented processOrders method should correctly perform the following actions:
- Initialize an
ExecutorServicewith a fixed thread pool of size 5 usingExecutors.newFixedThreadPool(5). - Iterate through the
orderIdslist. For eachorderId:- Create a
CompletableFuture<PaymentDetails>by callingCompletableFuture.supplyAsync(() -> fetchPaymentDetails(orderId), executorService). - Create a
CompletableFuture<ShippingInfo>by callingCompletableFuture.supplyAsync(() -> fetchShippingInfo(orderId), executorService). - Combine these two futures using the
thenCombinemethod. The combination logic should take thePaymentDetailsandShippingInfoobjects and construct a newProcessedOrderwith a summary string formatted as"Order [orderId]: Payment=[paymentDetails], Shipping=[shippingInfo]".
- Create a
- Collect the resulting
CompletableFuture<ProcessedOrder>for each order into aList. - Call the
shutdown()method on theExecutorServiceinstance to initiate an orderly shutdown. - Return the populated
List<CompletableFuture<ProcessedOrder>>.