cocotwo
cocotwo

Reputation: 1285

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)
    ...
}

Upvotes: 6

Views: 953

Answers (3)

Xr.
Xr.

Reputation: 1410

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.

Upvotes: 11

crowne
crowne

Reputation: 8534

I'd guess that the new thread starts running in parallel to the synchronized method.

someMethod() still holds its own lock which only prevents this method from being invoked simultaneously against this instance of the object.

The thread does not inherit the lock, and will only be inhibited by the lock if the thread tries to call someMethod() against the object which created it if someMethod() is currently executing for that object.

Upvotes: 0

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

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

Upvotes: 5

Related Questions