In this oracle example of intrinsic locks and many more, the monitor object is never declared as volatile, final or nor it has any distinction from any other regular object
public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } } public void inc2() { synchronized(lock2) { c2++; } } }
There are plenty of questions that debate volatile versus synchronization blocks
- volatile fields and synchronized blocks,
- difference between volatile and synchronized in java
- when to use volatile vs synchronization in multithreading in java,
- do you ever use the volatile keyword in java
and immutable objects
- what are immutable objects,
- immutability and synchronization in java
- immutable objects java concurreny)in multithreading.
As a side note, I understand this subtle difference between declaring an object final versus immutability why-can-final-object-be-modified and why declaring the lock object as final would not make it immutable.
However, we have the famous pattern of the singleton class lazy initialization where the use of the volatile
variables is essential.
public class SingletonDemo { private static volatile SingletonDemo instance; private SingletonDemo() { } public static SingletonDemo getInstance() { if (instance == null ) { synchronized (SingletonDemo.class) { if (instance == null) { instance = new SingletonDemo(); } } } return instance; } }
which in the above code example uses the Class object as lock.
Since for an object which is accessed by multiple threads you need to use some mechanism as above to ensure atomic access, why is that for intrinsic lock object there is no need for any special treatment?