Wiki Markup |
---|
Code that uses synchronization can sometimes be enigmatic and tricky to debug. Misuse of synchronization primitives is a common source of implementation errors. An analysis of the JDK 1.6.0 source code unveiled at least 31 bugs that fell into this category. \[[Pugh 08|AA. Java References#Pugh 08]\] |
Noncompliant Code Example (public
nonfinal lock object)
This noncompliant code example locks on a public
nonfinal object.
Code Block |
---|
|
public Object publicLock = new Object();
private void doSomething() {
synchronized(publicLock) {
// body
}
}
|
It is possible for untrusted code to change the value of the lock object and foil all attempts to synchronize.
Compliant Solution (final
lock object)
There are several common errors with synchronizing on objects:
- The synchronization might be on a non-final field. When the field is modified to reference a different object, threads that synchronize on the field no longer maintain exclusive locks, and run the danger of executing critical sections of code simultaneously
- The lock object might be accessible to hostile code, which can obtain the lock and hold it indefinitely.
Noncompliant Code Example (public
nonfinal lock object)
This noncompliant code example locks on a public
nonfinal objectThis compliant solution synchronizes on a private final
object and is safe from malicious or inadvertent manipulation.
Code Block |
---|
|
private finalpublic Object privateLockpublicLock = new Object();
private void doSomething() {
synchronized(privateLock) {
// body
}
}
|
Noncompliant Code Example (String
constant)
This noncompliant code example locks on a String
literal.
Code Block |
---|
|
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String _lock = "one";
synchronized(_lock) { /* ... */ }
|
Wiki Markup |
---|
A {{String}} literal is a constant and is interned. According to the Java API \[[API 06|AA. Java References#API 06]\], class {{String}} documentation: |
When the intern()
method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this String
object is returned.
Consequently, a String
constant behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if each instance of an object maintains its own field lock
, the field points to a common String
constant in the JVM. Trusted code that locks on the same String
constant renders all synchronization attempts inadequate. Likewise, hostile code from any other package can exploit this vulnerability.
Noncompliant Code Example (Boxed primitive)
This noncompliant code example locks on a boxed Integer
object.
Code Block |
---|
|
int lock = 0;
Integer Lock = lock; // Boxed primitive Lock will be shared
synchronized(Lock) { /* ... */ }
|
Boxed types are allowed to use the same instance for a range of integer values and consequently, suffer from the same problems as String
constants. Note that the boxed Integer
primitive is shared and not the Integer
object (new Integer(value)
) itself. In general, holding a lock on any data structure that contains a boxed value is insecure.
Noncompliant Code Example (Mutable lock object)
This noncompliant code example synchronizes on a mutable, nonfinal field and demonstrates no mutual exclusion properties.
Code Block |
---|
|
private Integer lock = new Integer(0);
private void doSomething() {
synchronized(lock) { /* ... */ }
}
public void setLock(Integer lockvalue) {
lock = lockValue;
}
|
This is because the thread that holds a lock on the nonfinal field object can modify the field's 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 lock mutability problem as opposed to the lock sharing issue specific to string literals and boxed primitives.
Compliant Solution (final
lock object)
This compliant solution synchronizes using a lock object that is declared as final
.
Code Block |
---|
|
private final Integer lock = new Integer(0);
private void doSomething() {
synchronized(lock) { /* ... */ }
}
// setValue() is disallowed
|
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)
Wiki Markup |
---|
This noncompliant code example uses a {{Boolean}} field to synchronize. However, there can only be two possible valid values ({{true}} and {{false}}, discounting {{null}}) that a {{Boolean}} can assume. Consequently, any other code that synchronizes on the same value can cause unresponsiveness and deadlocks \[[Findbugs 08|AA. Java References#Findbugs 08]\]. |
Code Block |
---|
|
private Boolean initialized = Boolean.FALSE;
synchronized(initialized) {
if (!initialized) {
// Perform initialization
initialized = Boolean.TRUE;
}
}
|
Compliant Solution (raw Object
lock object)
In the absence of an existing object to lock on, using a raw object to synchronize suffices.
Code Block |
---|
|
private final Object lock = new Object();
synchronized(lock) { /* ... */ }
|
publicLock) {
// body
}
}
|
It is possible for untrusted code to change the value of the lock object and foil all attempts to synchronize.
Noncompliant Code Example (publicly-accessible non-final lock object)
This noncompliant code example synchronizes on a nonfinal field and demonstrates no mutual exclusion properties.
Code Block |
---|
|
private Integer lock = new Integer(0);
private void doSomething() {
synchronized(lock) { /* ... */ }
}
public void setLock(Integer lockvalue) {
lock = lockValue;
}
|
This is because the thread that holds a lock on the nonfinal field object can modify the field's value to reference some other object. This might cause two threads that lock on the same field to actually not lock on the same object, causing them to execute critical sections of code simultaneously.
Compliant Solution (private
and final
lock object)
This compliant solution synchronizes using a lock object that is declared as final
.
Code Block |
---|
|
private final Integer lock = new Integer(0);
private void doSomething() {
synchronized(lock) { /* ... */ }
}
// setValue() is disallowed
|
Noncompliant Code Example (Boolean
lock object)
Wiki Markup |
---|
This noncompliant code example uses a {{Boolean}} field to synchronize. However, since the field is not {{final}}, there can be two possible valid values ({{true}} and {{false}}, discounting {{null}}) that a {{Boolean}} can assume. Consequently, any other code that synchronizes on the same value can cause unresponsiveness and deadlocks \[[Findbugs 08|AA. Java References#Findbugs 08]\]. |
Code Block |
---|
|
private Boolean initialized = Boolean.FALSE;
synchronized(initialized) {
if (!initialized) {
// Perform initialization
initialized = Boolean.TRUE;
}
}
|
Noncompliant Code Example (Boxed primitive)
This noncompliant code example locks on a non-final boxed Integer
object.
Code Block |
---|
|
int lock = 0;
Integer Lock = lock; // Boxed primitive Lock will be shared
synchronized(Lock) { /* ... */ }
|
Boxed types are allowed to use the same instance for a range of integer values and consequently, suffer from the same problems as Boolean
constants. Note that the boxed Integer
primitive is shared and not the Integer
object (new Integer(value)
) itself. In general, holding a lock on any data structure that contains a boxed value is insecure.
Noncompliant Code Example (final String
constant)
This noncompliant code example locks on a final String
literal.
Code Block |
---|
|
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String lock = "one";
synchronized(lock) { /* ... */ }
|
Wiki Markup |
---|
A {{String}} literal is a constant and is interned. According to the Java API \[[API 06|AA. Java References#API 06]\], class {{String}} documentation: |
When the intern()
method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this String
object is returned.
Consequently, a String
constant behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if each instance of an object maintains its own field lock
, the field points to a common String
constant in the JVM. Trusted code that locks on the same String
constant renders all synchronization attempts inadequate. Likewise, hostile code from any other package can exploit this vulnerabilityNote 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 is highly inadvisable. To prevent such modifications, declare the lock
field as final
.
Noncompliant Code Example (getClass()
lock object)
Synchronizing on return values of the Object.getClass()
method, rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass locks on a completely different Class
object (subclass's type).
...
This does not mean that a subclass locking using getClass()
can only synchronize on the Class
object of the base class. In fact, it will lock on its own Class
object, which may or may not be want the programmer had in mind.
Compliant Solution (
...
class name qualification)
Explicitly define the name of the class through name qualification (superclass in this example) in the synchronization block.
Code Block |
---|
|
synchronized(SuperclassName.class) {
// ...
}
|
Compliant Solution (2) (Class.forName()
)
This compliant solution uses the Class.forName()
method to synchronize on the superclass's Class
object.
...
The class object being synchronized must not be accessible to hostile code. For more information, see CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism.
Compliant Solution (2)
...
(Class.forName(
...
)
)
...
This compliant solution uses the Class.forName()
method to synchronize on the superclass's Class
object.
Code Block |
---|
|
synchronized(Class.forName("SuperclassName")) {
// ...
}
|
The class object being synchronized must not be accessible to hostile code. For more information, see CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism.
Noncompliant Code Example (collection view)
Finally, it is more important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.
Wiki Markup |
---|
When using synchronization wrappers, the synchronization object must be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a Collection view instead of the Collection object itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. |
Code Block |
---|
|
Map<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
Set<Integer> s = m.keySet();
synchronized(s |
Finally, it is more important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.
Noncompliant Code Example (collection view)
Wiki Markup |
---|
When using synchronization wrappers, the synchronization object must be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a Collection view instead of the Collection object itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. |
Code Block |
---|
|
Map<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
Set<Integer> s = m.keySet();
synchronized(s) { // Incorrectly synchronizes on s
for(Integer k : s) {
// Do something
}
}
|
Compliant Solution (collection lock object)
This compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block |
---|
|
// ...
synchronized(m) { // Synchronize on m, notIncorrectly synchronizes on s
for(Integer k : s) {
// Do something
}
}
|
...
Compliant Solution (collection lock object
...
)
This noncompliant code example uses a nonstatic lock object to guard access to a static
field. If two Runnable
tasks, each consisting of a thread are started, they will create two instances of the lock object and lock on each separately. This does not prevent either thread from observing an inconsistent value of counter
because the increment operation on volatile
fields is not atomic in the absence of proper synchronization. compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block |
---|
|
// ...
Map<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
synchronized(m) { // Synchronize on m, not s
for(Integer k : m) {
// Do something
}
}
|
Noncompliant Code Example (ReentrantLock
lock object)
This noncompliant code example incorrectly uses a ReentrantLock
as the lock object.
Code Block |
---|
|
final Lock |
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
Object lock = new ObjectReentrantLock();
public void run() {
synchronized(lock) {
counter++;
// ...
}
}
public static void main(String[] args) {
Runnable r1 = new CountBoxes();
Thread t1 = new Thread(r1);
Runnable r2 = new CountBoxes();
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
|
Noncompliant Code Example (method synchronization for static
data)
This problem usually comes up in practice when refactoring from intrinsic locking to the java.util.concurrent
utilities.
Compliant Solution (lock()
and unlock()
)
Instead of using the intrinsic locks of objects that implement the Lock
interface, including ReentrantLock
, use the lock()
and unlock()
methods provided by the Lock
interface.
Code Block |
---|
|
final Lock lock = new ReentrantLock();
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
|
Noncompliant Code Example (nonstatic lock object for static
data)
This noncompliant code example uses a nonstatic lock object to guard access to a static
field. If two Runnable
tasks, each consisting of a thread are started, they will create two instances of the lock object and lock on each separately. This does not prevent either thread from observing an inconsistent value of counter
because the increment operation on volatile
fields is not atomic in the absence of proper synchronizationThis noncompliant code example uses method synchronization to protect access to a static
class member.
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
public synchronized void run() {
counter++;
static volatile int counter;
// ...
Object }
lock // ...
}
|
The problem is that this lock is associated with each instance of the class and not with the class object itself. Consequently, threads constructed using different Runnable
instances may observe inconsistent values of the counter
.
Compliant Solution (1) (static
lock object)
This compliant solution declares the lock object as static
and consequently, ensures the atomicity of the increment operation.
Code Block |
---|
|
class CountBoxes implements Runnable {
static int counter;
// ...
static final Object lock = new Object();
public void run() {
synchronized(lock) {
counter++;
// ...
}
// ...
}
|
There is no requirement of declaring the counter
variable as volatile
when synchronization is used.
Compliant Solution (2) (intrinsic lock of class object)
This compliant solution uses the intrinsic lock of the class to synchronize the increment operation.
= new Object();
public void run() {
synchronized(lock) {
counter++;
// ...
}
}
public static void main(String[] args) {
Runnable r1 = new CountBoxes();
Thread t1 = new Thread(r1);
Runnable r2 = new CountBoxes();
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
|
Noncompliant Code Example (method synchronization for static
data)
This noncompliant code example uses method synchronization to protect access to a static
class member.
Code Block |
---|
|
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
public void run() {
synchronized(CountBoxes.class
public synchronized void run() {
counter++;
// ...
}
}// ...
}
// ...
}
|
...
The problem is that this lock is associated with each instance of the class and not with the class object itself. Consequently, threads constructed using different Runnable
instances may observe inconsistent values of the counter
.
Compliant Solution (static
lock object)
This noncompliant code example incorrectly uses a ReentrantLock
as compliant solution declares the lock object as static
and consequently, ensures the atomicity of the increment operation.
Code Block |
---|
|
final Lock lock = new ReentrantLock();
synchronized(lock) { /*class CountBoxes implements Runnable {
static int counter;
// ... */ }
|
This problem usually comes up in practice when refactoring from intrinsic locking to the java.util.concurrent
utilities.
Compliant Solution (lock()
and unlock()
)
This compliant solution uses the lock()
and unlock()
methods provided by the ReentrantLock
class.
Code Block |
---|
|
final Lock lock = new ReentrantLock();
lock.lock();
try {
private static final Object lock = new Object();
public void run() {
synchronized(lock) {
counter++;
// ...
} finally {}
// lock.unlock();...
}
|
There is no requirement of declaring the counter
variable as volatile
when synchronization is used.
Risk Assessment
Synchronizing on an incorrect variable can provide a false sense of thread safety and result in nondeterministic behavior.
...