...
Wiki Markup |
---|
The _private lock object_ idiom can be used to prevent this vulnerability. The idiom consists of a {{private}} object declared as an instance field. The {{private}} object must be explicitly used for locking purposes in {{synchronized}} blocks, within the class's methods. This intrinsic lock objectis belongsassociated towith anthe instance of the internal private object and is not associated with the class itself. Consequently, there is no lock contention between this class's methods and methods of a hostile class. \[[Bloch 01|AA. Java References#Bloch 01]\] |
The idiom can also be extended to protect static state by declaring the lock as private, static and final. If a static method is declared synchronized
, the intrinsic lock of the Class object is obtainedacquired before executing the statements in its body, 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 obtain access to the Class object. Reducing the accessibility of the class to package-private may offer some reprieve when using strategies other than internal locking.
This idiom can also be suitably used by classes designed for inheritance. If a superclass thread requests a lock on the object's monitor, a subclass thread can interfere with its operation because of lock reentrancy. For example, a subclass may use the superclass object's intrinsic lock for unrelated operations causing significant increase in lock contention. Also, excessive use of the same lock frequently results in deadlocks. This idiom separates the locking strategy of the superclass from that of the subclass. It also permits fine grained locking as opposed to coarse grained because multiple lock objects can then be used for seemingly unrelated operations. This increases overall responsiveness of the application.
...