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?
- No, that is exactly what synchronization prevents
- Correct: Yes, if any access path to the state is not synchronized, or if a compound action spans two synchronized calls
- Only if one method is static
- Only with more than eight threads
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.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction