Java Concurrency Interview

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

Why is locking on a String literal or a boxed Integer a bug?

String literals live in the string pool and small Integer values in the integer cache, so synchronized ("lock") in your class and the same literal in a library three layers away take the same monitor. You get contention you cannot see, and deadlocks between modules that know nothing about each other.

The same objection applies to locking on anything public: the object itself when it is handed to callers, or a Class object. The fix is a dedicated private field:

private final Object lock = new Object();

Note Boolean too. synchronized (someBoolean) locks one of exactly two objects in the whole JVM.

synchronized antipattern

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