Java 5 (released in 2004) was a game-changer for concurrent programming in the Java ecosystem. It introduced the powerful java.util.concurrent
package, providing high-level abstractions for threads, safe resource sharing, and scalable concurrency constructs.
๐ 1. java.util.concurrent Package
Java 5 introduced a comprehensive concurrency framework including:
✅ Executor Framework
Separates task submission from thread execution. It manages a pool of reusable threads.
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> System.out.println("Task executed!"));
executor.shutdown();
Key Interfaces: Executor, ExecutorService, ScheduledExecutorService
๐ 2. Callable and Future
Runnable
can't return results or throw exceptions. Callable<V>
solves this.
Callable<String> task = () -> "Result";
Future<String> future = executor.submit(task);
System.out.println(future.get());
๐ 3. Synchronization Utilities
a) ReentrantLock
Lock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
b) ReadWriteLock
ReadWriteLock rwLock = new ReentrantReadWriteLock();
rwLock.readLock().lock();
// safe read
rwLock.readLock().unlock();
๐ 4. Thread Coordination Tools
✅ CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
executor.submit(() -> {
// do work
latch.countDown();
});
latch.await(); // wait for all tasks
✅ CyclicBarrier
Used to wait for a group of threads to reach a common barrier point.
✅ Semaphore
Controls access to shared resources using permits.
๐ฆ 5. Concurrent Collections
Java 5 introduced thread-safe collections:
ConcurrentHashMap
CopyOnWriteArrayList
BlockingQueue
LinkedBlockingQueue
,ArrayBlockingQueue
๐ 6. Atomic Variables
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
Also includes: AtomicLong
, AtomicBoolean
, AtomicReference
๐งช 7. ThreadFactory & UncaughtExceptionHandler
✅ ThreadFactory
Used to customize thread creation in thread pools.
✅ UncaughtExceptionHandler
Catches unhandled exceptions in threads for centralized logging.
๐ Summary of Java 5 Concurrency Enhancements
Feature | Description |
---|---|
Executor Framework | Manages thread pools and task execution |
Callable & Future | Returns result from async tasks |
Locks | ReentrantLock, ReadWriteLock for fine control |
Synchronizers | CountDownLatch, CyclicBarrier, Semaphore |
Atomic Variables | Lock-free concurrency |
Concurrent Collections | Safe & scalable collections |
Utilities | ThreadFactory, UncaughtExceptionHandler |
๐ Final Thoughts
Java 5 laid the foundation for modern concurrency in Java. Almost every multithreaded framework today—like WebFlux, Spring Async, or CompletableFuture—builds upon these core constructs.
๐ Stay tuned for follow-up posts on:
- Java 6–7 concurrency improvements
- Java 8's CompletableFuture and parallel streams
- Java 21's Virtual Threads
Comments
Post a Comment