...
Wiki Markup |
---|
This vulnerability can be prevented by using a {{java.lang.Object}} declared within the class as {{private}} and {{final}}. The object must be explicitly used 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 methods of a hostile class. Joshua Bloch refers to this as the the "private lock object" idiom. \[[Bloch 01|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 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 object. The private final lock object idiom can be used to protect static data by declaring the lock as private
, static
and final
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.
This idiom is also suitable for classes designed for inheritance. If a superclass thread requests a lock on the object's monitor, a subclass thread can interfere with its operation. For example, a subclass may use the superclass object's intrinsic lock for performing unrelated operations, causing significant lock contention . Also, excessive use of the same lock frequently results in deadlocks. This idiom separates and deadlock. Separating the locking strategy of the superclass from that of the subclass prevents ensures they do not share a common lock. It also permits fine-grained locking because multiple lock objects can be used for seemingly unrelated operations. This increases , increasing the overall responsiveness of the application.
...