I am in doubt, what happens when a thread joins itself. i.e thread calls the join method on its own. I am not getting any error.
Sample :
public class JoinItself extends Thread { public void run() { System.out.println("Inside the run method "); System.out.println(Thread.currentThread().isAlive()); for(int i=0;i<5;i++) { try { System.out.println("Joining itself ..."); Thread.currentThread().join(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { JoinItself j = new JoinItself(); System.out.println(j.isAlive()); j.start(); System.out.println(j.isAlive()); System.out.println("Thread started ..."); } }
But Why? Should I get any error?
If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything. But this some point is non-deterministic.
A thread can be joined in Python by calling the Thread. join() method. This has the effect of blocking the current thread until the target thread that has been joined has terminated.
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.
thread::joinBlocks the current thread until the thread identified by *this finishes its execution. The completion of the thread identified by *this synchronizes with the corresponding successful return from join() .
The concept of a thread joining itself does not make sense.
It happens out that the join()
method uses the isAlive()
method to determine when to return from the join()
method. In the current implementation, it also does not check to see if the thread is joining itself.
In other words, the join()
method returns when and only when the thread is no longer alive. This will have the effect of waiting forever.
Should I get any error ?
I wouldn't expect an error. The javadocs for Thread.join()
do not say that this is an error, and it is just conceivable that some crazy person may use this as another way of doing a sleep
, so an undocumented error would be a bad idea.
I guess that Sun didn't think this was a case that was worth giving special attention to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With