If a method is marked synchronized by adding a keyword in its method definition, then the function can only be entered by one thread at a time.
It is shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked
in case of static method, Class object is used
public class Test { synchronized void instanceMethod() { // code } // same as void instanceMethod() { synchronized(this) { // code } } // ------------------------------------------------ static synchronized void staticMethod() { // code } // same as static void staticMethod() { synchronized(Test.class) { // code } }}
Java Monitor Pattern
Using this or Class as lock can be problematic because it can be accessed by outside world and someone can acquire lock causing issues
We can have a private lock and use it as follows:
public class Test { private static final myLock = new Object(); void method() { synchronized(myLock) { // code } }}
Reentrant Synchronization
Allowing a thread to acquire the same lock more than once enables reentrant synchronization
This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock
Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.
Intrinsic locks are reentrant
Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis
pthreads mutexes works on per-invocation basis and are not reentrant