Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: what happens when a new Thread is started from a synchronized block?

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)
    ...
}
like image 634
cocotwo Avatar asked Feb 26 '10 07:02

cocotwo


People also ask

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

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.

What happens if a thread throws an exception inside synchronized block?

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.

What happens when synchronized object is invoked?

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.

Can two threads access a synchronized method at the same time?

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.


2 Answers

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.

like image 88
Xr. Avatar answered Oct 13 '22 01:10

Xr.


No, only the original thread has the lock (because only one thread can hold a lock actually).

like image 25
Erich Kitzmueller Avatar answered Oct 13 '22 02:10

Erich Kitzmueller