Chapter TWENTY-SEVEN
Concurrency


Exam Objectives

Use synchronized keyword and java.util.concurrent.atomic package to control the order of thread execution.
Use java.util.concurrent collections and classes including CyclicBarrier and CopyOnWriteArrayList.

Answers

1. The correct answer is B.
Option A is false. ConcurrentSkipListMap is the only implementation of ConcurrentNavigableMap.
Option B is true. Whenever there's a modification to a CopyOnWriteArrayList list, it creates a new copy of the underlying array.
Option C is false. A static method can only use static variables, so it can only acquire the lock of static variables or the lock of variables defined inside the method.
Option D is false. A constructor cannot be synchronized because only one thread has access to the object when it is being created.


2. The correct answer is D.
Only option D performs the operation atomically. The other options perform the operation in two steps, which makes it vulnerable to race conditions.


3. The correct answer is D.
offerLast() inserts 10 to the Deque (the timeout value doesn't apply here because the Deque is not full). Then, pollLast() removes that value and returns it. At this point, the deque is empty, so pollFirst() will wait for 5 seconds to see if another thread inserts another value. Since this didn't happen, null is finally returned.


4. The correct answer is C.
The await() method throws an InterruptedException if the current thread was interrupted while waiting and a BrokenBarrierException if another thread was interrupted or timed out.