...
This noncompliant code example synchronizes on a mutable, nonfinal field instead of a raw Object
and demonstrates no mutual exclusion properties.
...
This is because the thread that holds a lock on the nonfinal field object can modify the referenced object's its value, allowing another thread that is blocked on the unmodified value to resume, at the same time, contending for the lock with a third thread that is blocked on the modified value. It is insecure to synchronize on a mutable field because this is equivalent to synchronizing on the field's contents. This is a mutual exclusion problem as opposed to the sharing issue discussed in the previous noncompliant code example.
Compliant Solution (final
lock object)
This compliant solution synchronizes using a lock object that is declared as final
.
Code Block | ||
---|---|---|
| ||
private final Integer semaphore = new Integer(0);
synchronized(semaphore) { /* ... */ }
|
As long as the lock object is final
, it is acceptable for the referenced object to be mutable. In this compliant solution, the Integer
object happens to be immutable by definition.
Noncompliant Code Example (Boolean
lock object)
...