13

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

DGH
  • 11,189
  • 2
  • 23
  • 24
  • 1
    Try it. Make another simple project and see what happens. – BeemerGuy Nov 23 '10 at 21:58
  • 3
    BeemerGuy: Perhaps I shall, at some point. However, I am not confident that trial and error alone will fully illuminate what is going on behind the scenes. There's always the chance someone else already knows, and can save me the time. – DGH Nov 23 '10 at 22:06

1 Answers1

14

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.

Martin Algesten
  • 13,052
  • 4
  • 54
  • 77
  • What you've pasted here is join(long millis). What about join()? I don't think the behaviors are the same for both methods. – DGH Nov 23 '10 at 22:33
  • please post a source reference.... I assume it's to the "official" Java java.lang.Thread.join(int) but I have no idea where that is located. – Jason S Nov 23 '10 at 22:56
  • `join()` calls `join(0)`. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java#l1317 – Number945 Feb 27 '21 at 17:46
  • And what if everything regarding Thread 1 by chance happens so much faster that Thread 2 hasn't even been created yet? (If Thread1 does Thread2.join() ) – LuckyLuke Skywalker May 07 '21 at 18:56