What is the use of "private final Object" locking in java multithreading ?
As far as my understanding goes, i think to make a class as thread safe we should either use intrinsic locking where we mark all the methods as synchronized & lock them on the Object's monitor using "this" ? OR we can replace the methods marked synchronized on "this" of the class with the private final Object lock inside the methods to lock on the generic Object lock to make it thread safe ?
Just for example code using intrinsic locking :
public class Counter{
// Locks on the object's monitor
public synchronized void changeValue() {
// ...
}
}
We can replace the above code with the following extrinsic lock:
public class Counter{
private final Object lock = new Object(); // private final lock object
public void changeValue() {
synchronized (lock) { // Locks on the private Object
// ...
}
}
}
Is it advisable to make the class as thread safe using extrinsic lock as above rather than using intrinsic locking ? Please correct me if my understanding is wrong here ?