DGH
DGH

Reputation: 11549

What is the behavior of Thread.join() in Java if the target has not yet started?

In a multi-threaded java program, what happens if a thread object T has been instantiated, and then has T.join() called before the thread has started? Assume that some other thread could call T.start() at any time after T has been instantiated, either before or after another thread calls T.join().

I'm asking because I think I have a problem where T.join() has been called before T.start(), and the thread calling T.join() hangs.

Yes, I know I have some design problems that, if fixed, could make this a non-issue. However, I would like to know the specifics of the join() behavior, because the only thing the Java API docs say is "Waits for this thread to die."

Upvotes: 13

Views: 3079

Answers (1)

Martin Algesten
Martin Algesten

Reputation: 13620

It will just return. See code below - isAlive() will be false before the thread starts, so nothing will happen.

   public final synchronized void join(long millis) 
    throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
        wait(0);
        }
    } else {
        while (isAlive()) {
        long delay = millis - now;
        if (delay <= 0) {
            break;
        }
        wait(delay);
        now = System.currentTimeMillis() - base;
        }
    }
    }

The code snippet is © Copyright Oracle 2006 and/or its affiliates, and can be found here. Licensed under Java Research License.

Upvotes: 14

Related Questions