Misuse of synchronization primitives is a common source of concurrency issues. Synchronizing on objects that may be reused can result in deadlock and nondeterministic behavior. Consequently, programs must never synchronize on objects that may be reused.
Noncompliant Code Example (Boolean
Lock Object)
This noncompliant code example synchronizes on a Boolean
lock object.
private final Boolean initialized = Boolean.FALSE; public void doSomething() { synchronized (initialized) { // ... } }
The Boolean
type is unsuitable for locking purposes because it allows only two values: true and false. Boolean literals containing the same value share unique instances of the Boolean
class in the Java Virtual Machine (JVM). In this example, initialized
refers to the instance corresponding to the value Boolean.FALSE
. If any other code were to inadvertently synchronize on a Boolean
literal with this value, the lock instance would be reused and the system could become unresponsive or could deadlock.
Noncompliant Code Example (Boxed Primitive)
This noncompliant code example locks on a boxed Integer
object.
private int count = 0; private final Integer Lock = count; // Boxed primitive Lock is shared public void doSomething() { synchronized (Lock) { count++; // ... } }
Boxed types may use the same instance for a range of integer values; consequently, they suffer from the same reuse problem as Boolean
constants. The wrapper object are reused when the value can be represented as a byte; JVM implementations are also permitted to reuse wrapper objects for larger ranges of values. While use of the intrinsic lock associated with the boxed Integer
wrapper object is insecure; instances of the Integer
object constructed using the new
operator (new Integer(value)
) are unique and not reused. In general, locks on any data type that contains a boxed value are insecure.
Compliant Solution (Integer)
This compliant solution locks on a nonboxed Integer
, using a variant of the private lock object idiom. The doSomething()
method synchronizes using the intrinsic lock of the Integer
instance, Lock
.
private int count = 0; private final Integer Lock = new Integer(count); public void doSomething() { synchronized (Lock) { count++; // ... } }
When explicitly constructed, an Integer
object has a unique reference and its own intrinsic lock that is distinct not only from other Integer
objects, but also from boxed integers that have the same value. While this is an acceptable solution, it can cause maintenance problems because developers can incorrectly assume that boxed integers are also appropriate lock objects. A more appropriate solution is to synchronize on a private final lock object as described in the final compliant solution for this rule.
Noncompliant Code Example (Interned String
Object)
This noncompliant code example locks on an interned String
object.
private final String lock = new String("LOCK").intern(); public void doSomething() { synchronized (lock) { // ... } }
According to the Java API class java.lang.String
documentation [API 2006]:
When the
intern()
method is invoked, if the pool already contains a string equal to thisString
object as determined by theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
object is returned.
Consequently, an interned String
object behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even when every instance of an object maintains its own lock
field, the fields all refer to a common String
constant. Locking on String
constants has the same reuse problem as locking on Boolean
constants.
Additionally, hostile code from any other package can exploit this vulnerability, if the class is accessible. See rule LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code for more information.
Noncompliant Code Example (String
Literal)
This noncompliant code example locks on a final String
literal.
// This bug was found in jetty-6.1.3 BoundedThreadPool private final String lock = "LOCK"; public void doSomething() { synchronized (lock) { // ... } }
String
literals are constant and are automatically interned. Consequently, this example suffers from the same pitfalls as the preceding noncompliant code example.
Compliant Solution (String
Instance)
This compliant solution locks on a noninterned String
instance.
private final String lock = new String("LOCK"); public void doSomething() { synchronized (lock) { // ... } }
A String
instance differs from a String
literal. The instance has a unique reference and its own intrinsic lock that is distinct from other String
object instances or literals. Nevertheless, a better approach is to synchronize on a private final lock object, as shown in the following compliant solution.
Compliant Solution (Private Final Lock Object
)
This compliant solution synchronizes on a private final lock object. This is one of the few cases in which a java.lang.Object
instance is useful.
private final Object lock = new Object(); public void doSomething() { synchronized (lock) { // ... } }
For more information on using an Object
as a lock, see rule LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code.
Risk Assessment
A significant number of concurrency vulnerabilities arise from locking on the wrong kind of object. It is important to consider the properties of the lock object rather than simply scavenging for objects on which to synchronize.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK01-J | medium | probable | medium | P8 | L2 |
Automated Detection
Some static analysis tools can detect violations of this rule.
Tool | Version | Checker | Description |
---|---|---|---|
The Checker Framework | 2.1.3 | Lock Checker | Concurrency and lock errors (see Chapter 6) |
Parasoft Jtest | 2024.1 | CERT.LCK01.SCS | Do not synchronize on constant Strings |
PVS-Studio | 7.34 | V6070 | |
SonarQube | 9.9 | S1860 | |
ThreadSafe | 1.3 | CCE_CC_REUSEDOBJ_SYNC | Implemented |
Bibliography
[API 2006] | Class String, Collections |
Locking | |
Synchronization | |
22 Comments
David Svoboda
I'm a little confused by the examples in this rule. It sounds like:
interned into a global table (eg String)
Sometimes I think Java should have had a Mutex class strictly for creating locks for synchroniziation.
Or am I misunderstanding things?
Dhruv Mohindra
java.util.concurrent
to the rescue. I'll get back to the concurrency section soon.David Svoboda
wrt Integer, why Integer? Couldn't you argue that any object modified by sync is bad. Why is Integer special?
WRT mutexes. I meant that Java should have used mutexes instead of allowing the developer to synchronize on any object. I suppose Java needs locks on any object, so that a bad multithreaded program can't bring down the JVM, but providing locks on every object to the programmer seems like too broad a feature for its usefulness. I'd rather it provide locks only on a specialized Mutex object. (just dreaming, of course, since Java is 14 years old now)
Dhruv Mohindra
Integer was just an example. Any boxed primitive is suspect.
David Svoboda
The Integer class is not mutable; and you only care that it is non-final in the NCCE. So that NCCE/CS set's text needs some attention. AFAICT mutable objects can be perfectly good locks, it's non-final you should be concerned with.
I would actually combine the mutable NCCE/CS set and merge it with the 1st NCCE/CS set, as the first NCCE/CS Result:
The remaining items would be:
I feel the non-static lock object for static data should go elsewhere. This rule is about objects that should never be synchronized on (such as strings, non-final objects, collection views, etc.) Synchronizing on a non-static lock object is sometimes appropriate, just not for the NCCE.
David Svoboda
I've made the changes to this rule that I suggested. But I'm still not happy with this rule. I'm feeling that the dangers expressed here and in LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code could be reorganized into something more concise. The examples in this rule are all worthwhile, but this rule deserves a better title than "sync. on the appropriate object". What do others think?
Dhruv Mohindra
An automatic detector would probably split this guideline into many individual violations, however, the current arrangement greatly simplifies the presentation from the pov of a reader who gets all the related information at one place.
Robert Seacord
I had the same thought as David. I think this should be reorganized into more concise guidelines. "sync. on the appropriate object" is clearly unenforceable.
Dhruv Mohindra
This might spiral into five or more guidelines which have the same solution. I can separate some of the examples like the Noncompliant Code Example (public nonfinal lock object) and Noncompliant Code Example (nonstatic lock object for static data). Is this good enough?
EDIT: I have split this guideline and created two more:
VOID CON34-J. Declare internal lock objects final and limit their accessibility
LCK06-J. Do not use an instance lock to protect shared static data
David Svoboda
Locking on static globally-accessible objects:
Locking on unexpected (wrong) object
Using intrinsic lock on a Lock object
Synching on a collection view rather than object (violates Collection API), violates encapsulation
Dhruv Mohindra
The Pugh 08 reference points this out in slide 31. From that it appears that the bugs are in the category of this guideline and possibly other related guidelines. I can't tell which interpretation is correct though it is a useful quote.
Your breakdown is correct. I am trying to figure out whether we really need to separate this material. The underlying problem is the same which leaves me a bit indecisive at this point.
Dhruv Mohindra
I think the title can be changed to "Do not synchronize on objects that may be canonicalized"
Robert Seacord (Manager)
i think i like the current title better. either that or "global literals"
Dhruv Mohindra
Ok. This book that I am reading uses the term canonicalization for this but I haven't heard anyone else call it by that name so let's stick to the current name. The book is also available online see Object canonicalization section in case you're interested.
Dhruv Mohindra
A Bishop
I don't understand CS "Compliant Solution (Integer)"
Why is the lock variable package protected?
Why is the lock variable mutable? particularly when the Lock variable is final?
Why is there a lock variable at all when it is only used to initialize the Lock variable?
Why are there two variables with names that only differ by the case of the first letter (lock and Lock)?
Why is Integer being used as a lock object when no Integer methods are being used? (i.e. this can just be object and the code still works)
David Svoboda
I changed the lock int to a 'count' variable, and increment it in doSomething...to make it appear that count has a purpose other than to initialize the Lock object. This also complies with OBJ01-J. Declare data members as private and provide accessible wrapper methods. It also avoids var names that differ only by case.
For the purpose of this guideline, the accessiblity and other details of 'count' are irrelevant, as it is only used to initialize the Lock object. (Also keep in mind that the Lock object will not share the same value as count once it gets incremented).
nina
The above article is saying do not synchronize on a shared object because it will cause unresponsive and deadlocks.
I can understand that it causes unresponsive but i am unclear how it will cause deadlocks.
Can you please explain or point me to some other resource which will help me understand this.
thanks in advance.
David Svoboda
Deadlock is addressed more fully in LCK07-J. Avoid deadlock by requesting and releasing locks in the same order. Violating this rule typically means your code shares locks unexpectedly. So it is fairly easy to imagine a scenario where two classes try to acquire two locks, and block on the second lock. If the locks are shared, then deadlock can arise easily.
nina
Thanks David for your reply.
I am still unclear. After the reading the article - LCK07-J. Avoid deadlock by requesting and releasing locks in the same order, it says that deadlocks occur when (1) two threads request the same two locks in different orders, and (2) each thread obtains a lock that prevents the other thread from completing its transfer.
which means that there should be at least 2 locks & the order of acquiring & releasing is different in 2 different threads.
In the code :
private
final
String lock =
"LOCK"
;
public
void
doSomething() {
synchronized
(lock) {
// ...
}
}
Thanks in advance.
David Svoboda
That code cannot deadlock by itself. It would have to be part of a system that grabbed one lock and held it while grabbing a second...which could be done by that code. The catch is that the lock, while it looks private, may not be...because the string may be canonicalized, and hence the lock may be acquired & released by some other module. So this code could participate in a deadlock scenario.
nina
thanks David.