cb7
cb7

Reputation: 523

How does thread.join() work conceptually?

From the docs:

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates

What I can't get my head around is that this is a method on a thread that's different to one it's being called from. So if a thread t1 calls another thread's t2.join(), t2 knows nothing about t1. So what's actually happening under the hood to make t1 wait for t2 for finish?

Upvotes: 0

Views: 4154

Answers (3)

There's a tiny bit extra info to add. OpenJDK really does (for join)

                while (isAlive()) {
                    wait(0);
                }

So, while one can cause a Thread calling tx.join to spuriously awake before tx is finished, it's not that easy to make it mistake the condition/running-status of tx which is stored in a private (& volatile) variable. The source comments also say about the latter:

     * [...] The historically named
     * `eetop` holds the address of the underlying VM JavaThread, and is set to
     * non-zero when the thread is started, and reset to zero when the thread terminates.
     * A non-zero value indicates this thread isAlive().

As for the javadoc, it does document this affair in words:

For platform threads, the 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.

Upvotes: 0

FrostNova
FrostNova

Reputation: 51

By looking at the Java source code:

calling t2.join() from t1 will make t1 wait on t2 object (t2 is a Thread, which is a subclass of Object). The wait will be forever as long as t1 is alive. When t2 thread finishes its work, it will call Object.notifyAll() so t1 awakens.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

The classic implementation of Thread.join (other implementations are possible, is to lock the Thread object, test to see if is alive and if not wait on the Thread object. As a thread exits, it locks its instance and calls notifyAll.

The choice of a public object as the lock is unfortunate.

Upvotes: 1

Related Questions