Multithreading in Java
Run tasks concurrently with threads and executors, and protect shared data with synchronisation.
Advanced
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Double> result = pool.submit(() -> heavyCalculation());
System.out.println(result.get()); // waits for the result
pool.shutdown();
Shared mutable data must be protected — with synchronized, locks, or thread-safe classes like AtomicInteger and ConcurrentHashMap — to avoid race conditions. Java 21's virtual threads make huge numbers of concurrent tasks cheap.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.