Java Multithreading Tutorial: Thread Lifecycle, Synchronization & Executors
Complete tutorial on Java Multithreading: Thread vs Runnable, synchronized keyword, volatile memory semantics, deadlocks, and ExecutorService thread pools.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrencyMastery {
private static final AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// Production standard: Using thread pool instead of manual Thread creation
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
// Thread-safe atomic increment without explicit synchronization lock
counter.incrementAndGet();
});
}
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("Final Thread-Safe Counter Value: " + counter.get());
}
}
1. Thread Creation: Why ExecutorService is Preferred
While you can create threads by subclassing Thread or implementing Runnable, production software should always manage concurrency through an ExecutorService. Manually creating threads incurs heavy OS context-switching overhead and risks unbounded thread creation under load.
2. The Java Memory Model & Volatile
Modern CPUs cache variables in L1/L2 hardware caches. When multiple threads access a shared field, one thread's update might not be immediately visible to another. Declaring a variable as volatile guarantees visibility and prevents instruction reordering across hardware threads.
3. Synchronization vs. Atomic Classes
The synchronized keyword enforces mutual exclusion via intrinsic monitor locks. However, for simple counters and flags, Java provides lock-free java.util.concurrent.atomic classes (like AtomicInteger) using hardware-level Compare-And-Swap (CAS) instructions for superior throughput.
- Avoid new Thread().start() in production web applications; use ExecutorService thread pools.
- Protect shared mutable state using either locks or atomic CAS data types.
- Java 21 introduces Virtual Threads for high-throughput lightweight I/O concurrency.
Frequently Asked Questions
What is a deadlock and how can it be prevented?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162