Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 916
DGH Avatar asked Nov 23 '10 21:11

DGH


People also ask

What happens if thread join is not called?

Yes, it is safe insofar as the thread will continue until completion by itself, you do not need to have a reference to the Thread object to keep it alive, nor will the behavior of the thread change in any way.

What is use of join () in threads of Java?

Join method in Java allows one thread to wait until another thread completes its execution. In simpler words, it means it waits for the other thread to die. It has a void type and throws InterruptedException.

What is the use of join () sleep wait () calls of thread?

The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.

What happens when a thread tries to join itself?

If the current thread calls join(), the thread is attempting to join with itself. In other words, the current thread is waiting until it completes. You guessed it: The current thread waits forever! By the way, to obtain access to the current thread's Thread object, call Thread's currentThread() method.


1 Answers

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.

like image 121
Martin Algesten Avatar answered Nov 03 '22 01:11

Martin Algesten