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 ?
The Oracle Secure coding standard contains every information you need.
Basically its for preventing this: Methods declared as synchronized and blocks that synchronize on the this reference both use the objectâs monitor (that is, its intrinsic lock). An attacker can manipulate the system to trigger contention and deadlock by obtaining and indefinitely holding the intrinsic lock of an accessible class, consequently causing a denial of service (DoS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With