...
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 obtained, 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.
In addition, this idiom Furthermore, it can 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. 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.
An object should use a private internal final lock object rather than its own intrinsic lock unless the class can guarantee that untrusted code cannot:
- Subclass the class or its superclass (trusted code is allowed to subclass the class)
- Create an object of the class (or its superclass, or subclass)
- Access or acquire an object instance of the class (or its superclass, or subclass)
If a superclass uses an internal private lock to synchronize shared data, subclasses must also use an internal private lock. However, if it uses intrinsic synchronization over the class object without documenting this policy, subclasses may not use intrinsic synchronization over their own class object, unless they explicitly document this locking policy. If the superclass documents this policy by stating that client-side locking is supported, the subclasses have the option of choosing between intrinsic locking over the class object and an internal private lock. Regardless of what is chosen, they subclasses must document the locking policy. Similarly, if a static method is declared synchronized
, the intrinsic lock of the Class object is obtained, and released when the method completes. The same restrictions listed above apply to static methods because 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.
If these restrictions are not met, the object's intrinsic lock is not trustworthy. If all conditions are satisfied, then the object gains no significant security from using a private internal lock object, and may synchronize using its own intrinsic lock.
...