Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will invoking two synchronized methods in one line cause a deadlock?

If a class has two synchronized methods:

public class A {
    public synchronized int do1() {...}
    public synchronized void do2(int i) {...}
}

Will invoking these two methods in one line cause a deadlock?

A a = new A();
a.do2(a.do1());
like image 611
Jonathan Avatar asked May 06 '12 14:05

Jonathan


People also ask

Can synchronized cause deadlock?

Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

Does synchronized prevent deadlock?

Synchronize does not prevent deadlock. On the contrary, synchronizing without taking proper precautions can introduce the potential for deadlock.

What will happen if a synchronized method is called by two threads?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

Can two synchronized methods in same class?

Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock.


1 Answers

Note that in your example, the two methods are not invoked concurrently.

There is a clear strict order between them - do2() cannot be invoked until do1() is done!

Also note, the code is equivalent to

A a = new A();
int temp = a.do1();
a.do2(temp);
like image 148
amit Avatar answered Jan 25 '23 06:01

amit