...
This noncompliant code example locks on a non-final object that is declared public
. It is possible that untrusted code can change the value of the lock object and foil the attempt any attempts to synchronize.
Code Block | ||
---|---|---|
| ||
public Object publicLock = new Object(); synchronized(publicLock) { // body } |
...
This compliant solution synchronized on a private final
object and is safe from malicious manipulation.
...
This noncompliant code example synchronizes on a mutable field instead of an object and is bound to demonstrate demonstrates no mutual exclusion properties, whatsoever. This is because the thread that holds a lock on the field can modify the referenced object's value which in turn allows another thread that is blocked on the unmodified value to resume, at the same time, granting access to a third thread that is blocked on the modified value. When aiming to modify a field, it is incorrect to synchronize on the same (or another) field as 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. Note that only the boxed Integer
primitive is shared as shown below and not the Integer
object (new Integer(value)
) itself.
...
Note that the instance of the raw object should not be changed from within the synchronized block. For example, creating and storing the reference of a new object into the lock
field. To prevent such modifications, declare the lock
field final
.
Noncompliant Code Example
Synchronizing on getClass()
rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass will end up locking locks on a completely different Class
object.
...