Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: more edits

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. Recall that there are two ways to synchronize access to shared mutable variables, method synchronization and block synchronization.

A method declared synchronized always uses the object's monitor (intrinsic lock) and so does code that synchronizes on the this reference using a synchronized block. This lock is available to any code that the object is available to; consequently, any code can lock on the object, and potentially cause a denial of service (DoS). Excessive An inappropriate synchronization policy can induce a DoS vulnerability because another class whose member locks on the same object, can fail to release the lock promptly. However, this requires the victim class to be accessible from the hostile class.

...

The idiom can also be extended to protect static state by declaring the lock as private, static and final. 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.

...

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 provide offer some reprieve when using strategies other than internal locking.

...

EX2: If a superclass of the class documents that it supports client-side locking and synchronizes on its class object, the class should also support client-side locking in the same way and document this policy. If notinstead it uses an internal private lock, it should document its inconsistent locking policy.

...