Java Concurrency Interview

synchronized, monitors, wait and notify question 33 of 180 mid

Can you synchronized on the same object from two methods and still have a race?

Locking is a convention, not a property of the data. If nine methods synchronize and one getter does not, the unsynchronized one can read a torn or stale value and the whole discipline is void. This is the "forgotten synchronization" antipattern, and it is usually one method added later by someone who did not notice.

The other half is compound actions. Both calls below are individually synchronized and the sequence is still a race:

if (!map.containsKey(k)) {   // thread-safe call
    map.put(k, v);           // also thread-safe, and this is still check-then-act
}

Atomicity must cover the whole invariant, which is what putIfAbsent and computeIfAbsent are for.

synchronized antipattern

Quiz yourself on synchronized, monitors, wait and notify Suggest a correction