Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This idiom can also be suitably used by classes designed for inheritance. If a superclass thread requests a lock on the class object's monitor, a subclass thread can interfere with its operation. Refer to the guideline CON36-J. Always synchronize on the appropriate object for more details.

Noncompliant Code Example

This noncompliant code example exposes the class object someObject to untrusted code. The untrusted code attempts to acquire a lock on the class object's monitor and upon succeeding, introduces an indefinite delay which holds up the synchronized changeValue() method from acquiring the same lock. Note that the untrusted code also violates CON07-J. Do not defer a thread that is holding a lock.

Code Block
bgColor#FFCCCC
public class SomeObj {
  public synchronized void changeValue() { // Locks on the class object's monitor
    // ...   
  }
}

// Untrusted code
synchronized (someObject) {
  while(true) {
    Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
  }
}

Compliant Solution

Thread-safe classes that use intrinsic synchronization may be protected by using the private lock object idiom and adapting them to use block synchronization. In this compliant solution, if the method changeValue() is called, the lock is obtained on a private Object that is both invisible and inaccessible from the caller.

...

For more details on using the private Object lock refer to CON36-J. Always synchronize on the appropriate object.

Risk Assessment

Exposing the class object to untrusted code can result in denial-of-service.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

CON10- J

low

probable

medium

P4

L3

References

Wiki Markup
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 52: "Document Thread Safety"

...