Posts

Showing posts with the label Fork Join Framework

Fork/Join Framework in Java — Parallelism with Work-Stealing

Image
The Fork/Join Framework (java.util.concurrent) is designed for parallelizing CPU-bound, divide-and-conquer tasks. It splits a big task into smaller subtasks (fork), runs them in parallel, and merges results (join). It's ideal for recursive algorithms (e.g., parallel sum, merge sort, matrix ops) and uses a work-stealing scheduler to balance load across worker threads. 1. When to use Fork/Join Large CPU-bound recursive tasks that can be divided into independent subtasks. Problems that follow divide-and-conquer pattern (array sum, parallel sort, tree algorithms). Not ideal for many short I/O-bound tasks — use ExecutorService for that. 2. Core Concepts ForkJoinPool — pool of worker threads optimized for Fork/Join tasks. ForkJoinTask — abstract base for tasks; two common subclasses: RecursiveTask<V> — returns a result. RecursiveAction — returns no result (void). Work-stealing — idle threads steal subtasks from busy threads...

Modern Concurrency Utilities in Java (java.util.concurrent)

Image
Traditional multithreading in Java using Thread , Runnable , synchronized , and wait/notify works, but it becomes difficult to scale in modern backend applications. Java introduced the java.util.concurrent package to simplify concurrency, improve performance, and avoid common threading issues. 1. Why java.util.concurrent? Older threading models had several limitations: Manual thread creation → expensive & slow Risk of race conditions Complex synchronization No proper thread lifecycle management The concurrency framework solves these problems using: Thread pools Locks Atomic variables Coordination tools Asynchronous computation 2. ExecutorService (Thread Pooling) ExecutorService manages threads efficiently and avoids creating too many threads. ExecutorService service = Executors.newFixedThreadPool(5); service.submit(() -> System.out.println("Task executed")); Types of Executor Services: newSingleThreadExecutor() – ...