Lock static class members

In my opinion, the following code fragment should lead to deadlock. The reason is that when thread t1 blocks the static firstData object, it acquired a lock on the class. Therefore, when it tries to block another static secondData object, the request should block.

However, the program runs fine and prints *** Successfully acquired both the locks

What is this blocking of static objects that are not here?

 public class Deadlock { public static void main(String[] args) { Thread t1 = new Thread(new DeadlockRunnable()); t1.start(); } } class DeadlockRunnable implements Runnable { static Object firstData = new Object(); static Object secondData = new Object(); public void run() { synchronized(firstData) { synchronized(secondData) { System.out.println("*** Successfully acquired both the locks"); } } } } 

For all those who answered that locks are on the object, instead of a class, see this

+6
source share
2 answers

Firstly, here you are mistaken:

The reason is that when thread t1 blocks the static firstData object, it acquired a lock on the class.

Locking a static object only blocks this object, not the class. You are blocking two separate objects.

The question you refer to about synchronized methods is not synchronized statements . These two related constructs work somewhat differently.


Secondly, even if you blocked the same object, your code will still not be blocked ( ideone ). Internal locks are reentrant. This means that the thread will not slow down itself if it tries to make the same lock twice.

Reentrant synchronization

Recall that a thread cannot get a lock belonging to another thread. But a thread can acquire a lock that it already owns. Allowing the thread to receive the same lock more than once provides resynchronization. This describes a situation where synchronized code, directly or indirectly, calls a method that also contains synchronized code, and both sets of code use the same lock. Without resynchronization, synchronized code must take many additional precautions to avoid blocking the flow.

A source

+14
source

"when thread t1 blocks the static firstData object, it acquired a lock for the class"
You donโ€™t know why you think so. t1 gets the lock on firstData, not on the containing class. There is no possible deadlock in your code.

EDIT
Following your comment, the link deals with the difference between the two ads:

 public synchronized method() // lock on the instance (this) public static synchronized method() // lock on the class (Myclass.class) 

But there is no connection with dead ends.

+1
source

Source: https://habr.com/ru/post/913660/


All Articles