Important Interfaces and Classes in Java Concurrency

Java’s concurrency framework, primarily housed in the java.util.concurrent package, provides a rich set of interfaces and classes to manage multithreading, synchronization, and concurrent data structures. Below is a list of the most important interfaces and classes for Core Java concurrency, with brief descriptions—perfect for interview prep or practical use.


Key Interfaces

  1. Executor
    • Purpose: Base interface for executing tasks asynchronously.
    • Key Method: void execute(Runnable command)
    • Role: Decouples task submission from execution mechanics.
  2. ExecutorService (extends Executor)
    • Purpose: Manages thread pools and task lifecycles, supporting Callable tasks with results.
    • Key Methods: submit(), shutdown(), invokeAll()
    • Role: Core interface for thread pool implementations.
  3. ScheduledExecutorService (extends ExecutorService)
    • Purpose: Adds scheduling capabilities for delayed or periodic tasks.
    • Key Methods: schedule(), scheduleAtFixedRate(), scheduleWithFixedDelay()
    • Role: Essential for timed executions.
  4. Callable<V>
    • Purpose: Represents a task that returns a result and may throw an exception.
    • Key Method: V call() throws Exception
    • Role: Used with ExecutorService for tasks with return values (vs. Runnable).
  5. Future<V>
    • Purpose: Represents the result of an asynchronous computation.
    • Key Methods: get() (blocks for result), isDone(), cancel()
    • Role: Tracks and retrieves results from Callable tasks.
  6. BlockingQueue<E>
    • Purpose: Thread-safe queue that blocks on insertion/removal when full/empty.
    • Key Methods: put(), take(), offer(), poll()
    • Role: Foundation for producer-consumer patterns.
  7. BlockingDeque<E> (extends BlockingQueue)
    • Purpose: Double-ended blocking queue.
    • Key Methods: putFirst(), takeLast(), etc.
    • Role: Supports LIFO/FIFO operations in concurrent settings.
  8. ConcurrentMap<K, V> (extends Map)
    • Purpose: Thread-safe map with atomic operations.
    • Key Methods: putIfAbsent(), replace(), remove(key, value)
    • Role: Enhances Map for concurrent access.
  9. Lock
    • Purpose: Alternative to synchronized blocks with more flexibility.
    • Key Methods: lock(), unlock(), tryLock()
    • Role: Fine-grained control over locking.
  10. ReadWriteLock
    • Purpose: Provides separate locks for reading (shared) and writing (exclusive).
    • Key Methods: readLock(), writeLock()
    • Role: Optimizes for read-heavy scenarios.

Key Classes

  1. ThreadPoolExecutor
    • Purpose: Highly configurable thread pool implementation of ExecutorService.
    • Key Features: Custom thread count, queue type, rejection policy.
    • Usage: new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue)
  2. ScheduledThreadPoolExecutor (extends ThreadPoolExecutor, implements ScheduledExecutorService)
    • Purpose: Thread pool for scheduled tasks.
    • Key Features: Executes tasks with delays or periodically.
    • Usage: Executors.newScheduledThreadPool(corePoolSize)
  3. Executors
    • Purpose: Factory class for creating ExecutorService instances.
    • Key Methods:
      • newFixedThreadPool()
      • newCachedThreadPool()
      • newSingleThreadExecutor()
      • newScheduledThreadPool()
    • Role: Simplifies thread pool creation.
  4. ForkJoinPool (implements ExecutorService)
    • Purpose: Optimized for recursive, divide-and-conquer tasks (work-stealing).
    • Key Features: Parallelism based on CPU cores.
    • Usage: Executors.newWorkStealingPool() or new ForkJoinPool()
  5. ArrayBlockingQueue<E> (implements BlockingQueue)
    • Purpose: Fixed-size, array-based blocking queue.
    • Key Features: FIFO, bounded capacity.
    • Usage: new ArrayBlockingQueue<>(capacity)
  6. LinkedBlockingQueue<E> (implements BlockingQueue)
    • Purpose: Linked-list-based blocking queue, optionally bounded.
    • Key Features: FIFO, dynamic size (default unbounded).
    • Usage: new LinkedBlockingQueue<>()
  7. PriorityBlockingQueue<E> (implements BlockingQueue)
    • Purpose: Priority-ordered blocking queue (unbounded).
    • Key Features: Elements sorted by natural order or Comparator.
    • Usage: new PriorityBlockingQueue<>()
  8. ConcurrentHashMap<K, V> (implements ConcurrentMap)
    • Purpose: Thread-safe hash map with high concurrency.
    • Key Features: Lock-free reads, segmented writes.
    • Usage: new ConcurrentHashMap<>()
  9. CopyOnWriteArrayList<E> (implements List)
    • Purpose: Thread-safe list for read-heavy scenarios.
    • Key Features: Creates a new copy on write, reads use snapshot.
    • Usage: new CopyOnWriteArrayList<>()
  10. ReentrantLock (implements Lock)
    • Purpose: Reentrant lock (same thread can lock multiple times).
    • Key Features: Supports fairness, interruptible locking.
    • Usage: new ReentrantLock()
  11. ReentrantReadWriteLock (implements ReadWriteLock)
    • Purpose: Provides read/write locks for concurrent access.
    • Key Features: Multiple readers, single writer.
    • Usage: new ReentrantReadWriteLock()
  12. CountDownLatch
    • Purpose: Synchronization aid—threads wait until a count reaches zero.
    • Key Methods: await(), countDown()
    • Usage: new CountDownLatch(count)
  13. CyclicBarrier
    • Purpose: Threads wait until a set number reach a barrier point.
    • Key Methods: await()
    • Usage: new CyclicBarrier(parties)
  14. Semaphore
    • Purpose: Controls access to a resource pool with permits.
    • Key Methods: acquire(), release()
    • Usage: new Semaphore(permits)

Practical Example

import java.util.concurrent.*;

public class ConcurrencyExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<Integer> future = executor.submit(() -> {
            Thread.sleep(1000);
            return 42;
        });
        System.out.println("Result: " + future.get()); // Blocks until result
        executor.shutdown();

        CountDownLatch latch = new CountDownLatch(1);
        new Thread(() -> {
            System.out.println("Task running...");
            latch.countDown();
        }).start();
        latch.await(); // Wait for task
        System.out.println("Task completed.");
    }
}
  • Output:Result: 42 Task running... Task completed.

Key Notes :

  • Interfaces: Know ExecutorService, Callable, Future—they’re the backbone of task execution.
  • Classes: Focus on ThreadPoolExecutor, ConcurrentHashMap, and synchronization tools like CountDownLatch.
  • Use Cases: Match types to scenarios (e.g., Semaphore for resource limits, ForkJoinPool for parallelism).

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *