Java Concurrency Flashcards
7 cards from real OCP practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Java Concurrency flashcards as text
Which Java 8+ feature provides a non-blocking way to chain asynchronous computations and handle errors?
Answer: CompletableFuture
`CompletableFuture` supports fluent chaining of async stages with methods like `thenApply`, `thenCompose`, and `exceptionally`.
What is a thread starvation scenario in Java?
Answer: A thread is perpetually denied CPU time because higher-priority threads always run first
Starvation occurs when a thread cannot gain regular CPU access because other threads with higher priority or faster scheduling always preempt it.
Which method of `BlockingQueue` removes and returns the head element, waiting up to a specified time if necessary?
Answer: poll(long timeout, TimeUnit unit)
`poll(timeout, unit)` waits up to the specified time for an element to become available, returning `null` if the timeout expires.
In Java's memory model, what does a `synchronized` block guarantee upon exit?
Answer: All writes made inside the block are flushed to main memory and visible to threads that subsequently synchronize on the same monitor
Exiting a `synchronized` block performs an unlock that establishes a happens-before relationship with subsequent locks on the same monitor.
What is the difference between `Executors.newFixedThreadPool(n)` and `Executors.newCachedThreadPool()`?
Answer: Fixed pool uses a bounded thread count with an unbounded queue; cached pool creates new threads on demand and reuses idle ones
`newFixedThreadPool` keeps exactly n threads with a `LinkedBlockingQueue`, while `newCachedThreadPool` dynamically creates threads and reuses idle ones with a 60-second keepalive.
Which atomic operation does the `AtomicInteger.compareAndSet(expect, update)` method perform?
Answer: Sets value to update only if current value equals expect, atomically
CAS atomically checks if the current value matches `expect` and only then updates to `update`, returning `true` on success.
What does the `Exchanger` class enable two threads to do?
Answer: Swap objects at a synchronization point where each thread presents an object and receives the other's object
`Exchanger` provides a rendezvous point where two threads can swap data; each call to `exchange()` blocks until the partner thread also calls `exchange()`.