Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread inherits lock from spawning thread

The following code did not block when the spawned thread tried to obtain the lock on itself.

Does the spawned thread inherits locks from the spawning thread?

Here's the code:

public class A {

    public void methodA() {
        public class SpawnedThread extends Thread {
            public void run() {
                synchronized(this) {
                ...
            }
       };

       SpawnedThread spawnedThread= new SpawnedThread ();
       synchronized(spawnedThread) {
            spawnedThread.start();
            spawnedThread.join();
      };
      ...
   }
}
like image 779
user3850049 Avatar asked May 13 '26 02:05

user3850049


1 Answers

Threads don't inherit locks from other threads, something else is going on here.

In your example the thread that is running methodA has to take the lock on the spawnedThread before it can enter the synchronized block.

Then when the spawnedThread runs it must acquire the lock on itself in order to enter the synchronized block in the run method.

So the methodA thread has the lock and spawnedThread is trying to get the same lock. But it won't deadlock because Thread.join performs waits where it gives up the lock, see the api documentation for Thread.join:

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

The version of Thread.join without a timeout value takes the lock on the thread it's joining, gives it up, and goes dormant. It doesn't wake up until one of the following happens:

1) the thread being joined finishes (sending a notification that wakes the waiting thread)

2) the joining thread is interrupted (meaning something calls interrupt on it, which doesn't happen in this example)

3) the joining thread wakes up on its own (a "spurious wakeup", which is rare, a result of a race condition)

I'm not clear on how you would change the locks to get a deadlock here as you described in your comment, if you want that answered please add that version of the code to your question.

like image 102
Nathan Hughes Avatar answered May 15 '26 14:05

Nathan Hughes