Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop thread returning before Join() is called

This is purely a theoretical question as I'm not sure the conditions to cause this issue would be common.

Say for example you have a thread that you kick off with it's start method:

Thread c = new Thread();
c.start();

Then directly after, you call the Join() method on the thread to tell the method you are in to wait until the thread had been executed to continue.

c.join();

Isn't it a possibility that the thread could possibly be executed and finish before the join method is called, therefore leaving the method unaware that it had to wait for c to finish before it continued? I suppose you could try calling the join() method before you call the start() method, yet whenever I've tried this in test cases, there is an error.

Anyone know a possible fix for this, or does the JVM handle it? As I said I haven't been able to trigger this sort of situation, but theoretically it is possible...

like image 736
user898465 Avatar asked Feb 09 '12 14:02

user898465


People also ask

What if thread finishes before join?

Thread will continue to run (usually parallel with other threads) until it is either blocked by some synchronization operation or thread exits the its start function. The thread can wait with pthread_join() for other threads to finish execution successfully.

Why would threads call the thread join () method?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

Does join terminate a thread?

join() does not do anything to thread t . The only thing it does is wait for thread t to terminate.

What is the role of join () in multithreading?

Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. join() will make sure that t is terminated before the next instruction is executed by the program.


1 Answers

According to the Thread#join(long millis) source code, the isAlive() method is used to check the thread state.

/**
 * Tests if this thread is alive. A thread is alive if it has
 * been started and has not yet died.
 *
 * @return  <code>true</code> if this thread is alive;
 *          <code>false</code> otherwise.
 */
public final native boolean isAlive();

This method obviously returns false if the thread has finished, so thread.join() will immediately exit.

like image 61
Alexander Pavlov Avatar answered Sep 23 '22 06:09

Alexander Pavlov