What concurrency tools does Java give you, and when do you use each?
Answer
synchronized / ReentrantLock: protect shared mutable state with mutual exclusion.volatile: visibility of a simple flag.Atomic* / LongAdder: lock-free counters.ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue: thread-safe collections for shared data and producer/consumer.ExecutorService: thread pools to run tasks; CompletableFuture: compose async steps.- Virtual threads (Java 21): simple blocking style for massive I/O concurrency.
- Best rule: avoid shared mutable state; prefer immutable objects and message passing.
Practice this question in Repaso