Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "private final Object" locking in java multithreading?

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 ?

like image 282
rookie_ron Avatar asked Oct 17 '13 06:10

rookie_ron


1 Answers

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).

like image 150
Ezzored Avatar answered Oct 03 '22 10:10

Ezzored