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 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, 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.

ToolVersionCheckerDescription
The Checker Framework

2.1.3

Lock CheckerConcurrency and lock errors (see Chapter 6)
Parasoft Jtest
2024.1
CERT.LCK01.SCSDo not synchronize on constant Strings
PVS-Studio

7.32

V6070
SonarQube
9.9
S1860
ThreadSafe
1.3

CCE_CC_REUSEDOBJ_SYNC

Implemented

Bibliography

[API 2006]

Class String, Collections

[Findbugs 2008]


[Miller 2009]

Locking

[Pugh 2008]

Synchronization

[Tutorials 2008]

Wrapper Implementations



22 Comments

  1. I'm a little confused by the examples in this rule. It sounds like:

    • Don't synchronize on a global object like a Class, or on an object
      interned into a global table (eg String)
    • Don't modify an object while synchronized on that object like Integer
    • Do create raw Objects for synchronization (which I have successfully done)
      Sometimes I think Java should have had a Mutex class strictly for creating locks for synchroniziation.

    Or am I misunderstanding things?

      • Right
      • Even better, do not use Integer for synchronization (instead of relying on the fact that no one will modify the ref)
      • Right. One of the rare uses of a raw object.

      java.util.concurrent to the rescue. I'll get back to the concurrency section soon.

      1. 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)

        1. Integer was just an example. Any boxed primitive is suspect.

  2. 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:

    • An NCCE whose lock is a private non-final Object with a setter method
    • An CS whose lock is private final raw Object (obviously with no setter method)

    The remaining items would be:

    • NCCE non-final boolean lock object
    • NCCE String constant final lock object
    • NCCE Boxed primitive non-final lock object
    • NCCE getClass() class object. (Should reference CON04-J)
    • CS object.class. (Should ensure that class is package-private, reference CON04-J)
    • CS Class.forName(...). (Should ensure that class is package-private, reference CON04-J)
    • NCCE Collection view, and CS Collection object itself (fill out CS more)
    • NCCE ReentrantLock (along with corresponding CS)

    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.

    • In the 1st CS the lock object should be private.
    • The 2nd CS should prob be removed, as the 1st CS passes CON04-J.
    1. 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?

      1. 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.

        1. 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.

          1. 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

            1. 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

              • If we want to subdivide this rule futher, the breakdown I see is:

              Locking on static globally-accessible objects:

              • NCCE boolean lock object
              • NCCE boxed primitive
              • NCCE string constant

              Locking on unexpected (wrong) object

              • NCCE getClass() object
              • CS classname qualification
              • class.forName() qualification

              Using intrinsic lock on a Lock object

              • NCCE Reentrant lock object)
              • CS lock() and unlock()

              Synching on a collection view rather than object (violates Collection API), violates encapsulation

              • NCCE Collection view
              • CS collection lock object
              1. 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.

  3. I think the title can be changed to "Do not synchronize on objects that may be canonicalized"

    1. i think i like the current title better. either that or "global literals"

      1. 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.

    • In the following sentence, could the "can" in bold be replaced with a "may" because this is a possibility? Something like "It may rain tomorrow" instead of "it can rain tomorrow".

    "While this is an acceptable solution, it can cause maintenance problems because developers can incorrectly assume that boxed integers are appropriate lock objects."

    • private final are keywords and always in lowercase...should they appear as lower case and in non-code font in the headings?
  4. 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)

    1. 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).

  5. 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. 

    1. 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.

  6. 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) {
        // ...
      }
    }
    There is only 1 lock - "LOCK" , so there is no question of "two locks in different order"?
    So can you please explain how this code causes deadlock?

    Thanks in advance.

    1. 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.

  7. thanks David.