views:

164

answers:

3

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)
    ...
}
+5  A: 

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

ammoQ
@ammoQ: ok great, +1 to you and Xr. I validated Xr answer because he needs points :) That said now I've got another question, related but different (and I've seen it's better to open a new question here)
cocotwo
+8  A: 

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 stead 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.

Xr
A: 

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.

crowne