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());
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.
Synchronize does not prevent deadlock. On the contrary, synchronizing without taking proper precautions can introduce the potential for deadlock.
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.
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.
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);
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