nano7
nano7

Reputation: 2493

Java: if joining Threads does not work: break or continue?

what is recommended to do if joining threads does not work?

        for (List t : threads) {
           try {
              t.join();
           } catch (InterruptedException e) {
              log.error("Thread " + t.getId() + " interrupted: " + e);
              // and now?
           }
         }

is it recommended to break then (what happens then with the other threads which are not joined yet?) or should you at least try to join the rest of the threads and then go on?

Thanks for advices!

==> Conclusion: You should try again to join the specific thread t or you should interrupt this specific thread t and go on.

     for (List t : threads) {
        try {
          t.join();
       } catch (InterruptedException e) {    
            try {
                // try once! again:
                t.join();
            } catch (InterruptedException ex) {
                // once again exception caught, so:
                t.interrupt();
            }
         }
       }

so what do you think about this solution? and is it correct to do "t.interrupt()" or should it be Thread.currentThread().interrupt(); ?

thanks! :-)

Upvotes: 4

Views: 585

Answers (1)

dacwe
dacwe

Reputation: 43504

You get an InterruptedException because some other thread interrupted this, the joining, thread and not because the join didn't "work". Quoted from the API documentation:

InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.


I would advice you to rejoin the thread again, example:

for (List t : threads) {
    while (true) {
        try {
            t.join();
            break;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // ... and ignore the interrupt
        }
    }
}

Upvotes: 2

Related Questions