Java: what happens when a new thread starts from a synchronized block?

The first question is here: this is a very short but fundamental thing in Java that I don't know about ...

In the following case, did the run() method somehow execute with the lock that somemethod() actually acquired?

 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) ... } 
+6
java multithreading synchronization locking
source share
3 answers

Not. run() runs in its own context, by synchronization. There are no locks in it. If this happened, you would either have a dead end or violate specifications specifying that only one thread can hold an object lock at any given time.

If run() was to call somemethod() again on the same object, it would have to wait for somemethod() to call, which created it to complete first.

+10
source share

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

+5
source share

I assume that the new thread starts running in parallel to the synchronized method.

someMethod () still retains its own lock, which only prevents this method from being called simultaneously with this instance of the object.

The thread does not inherit the lock and will only be locked by the lock if the thread tries to call someMethod () on the object that created it, if this someMethod () method is currently running for this object.

0
source share

All Articles