There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization. Methods declared as synchronized and blocks that synchronize on the this
reference both use the objectâs monitor (that is, its intrinsic lock). An attacker can manipulate the system to trigger contention and deadlock by obtaining and indefinitely holding the intrinsic lock of an accessible class, consequently causing a denial of service (DoS).
One technique for preventing this vulnerability is the _private lock object_ idiom \[ [Bloch 2001|AA. References#Bloch 01]\]. This idiom uses the intrinsic lock associated with the instance of a private final {{ Wiki Markup java.lang.Object
}} declared within the class instead of the intrinsic lock of the object itself. This idiom requires the use of synchronized blocks within the classâs methods rather than the use of synchronized methods. Lock contention between the classâs methods and those of a hostile class becomes impossible because the hostile class cannot access the private final lock object.
Static methods and state also share this vulnerability. When a static method is declared synchronized
, it acquires the intrinsic lock of the class object before any statements in its body are executed, and it releases the intrinsic lock when the method completes. Untrusted code that has access to an object of the class, or of a subclass, can use the getClass()
method to gain access to the class object and consequently manipulate the class object's intrinsic lock. Protect static data by locking on a private static final Object
. Reducing the accessibility of the class to package-private provides further protection against untrusted callers.
...
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a957b66a-d8aa-426c-af9c-4c7eb05a7e7d"><ac:plain-text-body><! [CDATA[ [[Bloch 2001AA. References#Bloch 01] ] | Item 52. Document Thread Safety ]]></ac:plain-text-body></ac:structured-macro> |
...