Concurrency
Concurrency allows your program to do multiple things simultaneously. It’s essential for modern applications to utilize multi-core processors and handle multiple users.1. Threads vs. Processes
- Process: An executing program (e.g., the JVM itself). It has its own isolated memory space.
- Thread: A lightweight unit of execution within a process. Threads share the same memory space.
Creating a Thread
2. Executor Framework
Manually creating threads (new Thread()) is expensive and error-prone. If you create 10,000 threads, you might crash the OS.
Executors manage a pool of threads for you. You just submit tasks, and the pool handles the execution.
Types of Pools
newFixedThreadPool(n): Fixed number of threads. Good for predictable loads.newCachedThreadPool(): Creates threads as needed, reuses idle ones. Good for many short-lived tasks.newSingleThreadExecutor(): One thread. Ensures tasks run sequentially.
3. Callable & Future
Runnable returns void. What if you want a result? Use Callable.
A Future represents the result of an asynchronous computation. It’s a placeholder for a value that will arrive later.
4. Synchronization
When multiple threads access shared data (like a counter), race conditions occur. Two threads might read “5”, increment it, and both write “6”, losing one increment.synchronized Keyword
Ensures only one thread can execute a block at a time. It’s like a lock on a door.
Atomic Classes
For simple variables,AtomicInteger is faster and lock-free.
5. CompletableFuture (Java 8+)
Future.get() blocks the thread. CompletableFuture allows you to build non-blocking, reactive pipelines (similar to Promises in JavaScript).
6. Virtual Threads (Java 21)
Game Changer: Traditional threads are mapped 1:1 to OS threads. They are heavy (2MB stack). You can only have a few thousand. Virtual Threads are lightweight threads managed by the JVM. You can create millions of them.Summary
- Threads: Basic unit of concurrency.
- Executors: Manage thread pools.
- Synchronization: Protect shared state from race conditions.
- CompletableFuture: Compose async tasks.
- Virtual Threads: High-throughput concurrency for Java 21+.