Versions Compared

Key

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

The synchronized keyword is used to acquire a mutual-exclusion lock so that no other thread can acquire the lock while it is being held by the executing thread. There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization.

A method declared as synchronized always uses the object’s monitor (intrinsic lock), as does code that synchronizes on the this reference using a synchronized block. Poorly synchronized code is prone to contention and deadlock. An attacker can manipulate the system to trigger these conditions and cause a denial of service by obtaining and indefinitely holding the intrinsic lock of an accessible class.

Wiki Markup
This vulnerability can be prevented using a  {{java.lang.Object}} declared {{private}} and {{final}} within the class. The object must be used explicitly for locking purposes in {{synchronized}} blocks within the class’s methods. This intrinsic lock is associated with the instance of the private object and not the class. Consequently, there is no lock contention between this class’s methods and the methods of a hostile class. Bloch refers to this technique as the “private lock object” idiom \[[Bloch 2001|AA. Java References#Bloch 01]\].

Static state has the same potential problem. If a static method is declared synchronized, the intrinsic lock of the class object is acquired before any statements in its body are executed, and the lock is released when the method completes. Any untrusted code that can access an object of the class, or a subclass, can use the getClass() method to gain access to the class lock. Static data can be protected by locking on a private static final Object. Reducing the accessibility of the class to package-private adds further protection against untrusted callers.

...

Thread-safe public classes that may interact with untrusted code must use a private final lock object. Existing classes that use intrinsic synchronization must be refactored to use block synchronization on such an object. In this compliant solution, calling changeValue() obtains a lock on a private final Object instance that is inaccessible from callers outside the class's scope.

...

The untrusted code attempts to acquire a lock on the class object’s monitor and, upon succeeding, introduces an indefinite delay that prevents the synchronized changeValue() method from acquiring the same lock.

...

In this compliant solution, ChangeValue() obtains a lock on a static private Object that is inaccessible to the caller.

...