First question here: it is a very short yet fundamental thing in Java that I don't know...
In the following case, is the run()
method somehow executed with the lock that somemethod()
did acquire?
public synchronized void somemethod() {
Thread t = new Thread( new Runnable() {
void run() {
... <-- is a lock held here ?
}
}
t.start();
...
(lengthy stuff performed here, keeping the lock held)
...
}
Can two threads call two different synchronized instance methods of an Object? 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.
Other threads will be able to continue synchronizing, and calling wait and notify. If the thread with the exception is holding some critical program logic resource, you may need to use try-finally to ensure it is released. Save this answer.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
Two threads cannot access the same synchronized method on the same object instance. One will get the lock and the other will block until the first thread leaves the method. In your example, instance methods are synchronized on the object that contains them.
No. run()
starts in its own context, synchronization-wise. It doesn't hold any locks. If it did, you would either have a deadlock or it would violate the specs that state that only one thread may hold the lock on an object at any given time.
If run()
was to call somemethod()
again on the same object, it would have to wait for the somemethod()
call that created it to complete first.
No, only the original thread has the lock (because only one thread can hold a lock actually).
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