Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Difference in usage between Thread.interrupted() and Thread.isInterrupted()?

Java question: As far as I know, there are two ways to check inside a thread whether the thread received an interrupt signal, Thread.interrupted() and Thread.isInterrupted(), and the only difference between them is that the former resets the internal interrupted flag.

So far, I've always used Thread.isInterrupted() and never had any problems with it. Then again, most tutorials I've seen recommend using Thread.interrupted(). Is there any specific reason for that?

like image 227
python dude Avatar asked Dec 14 '09 22:12

python dude


People also ask

What does thread currentThread () interrupt () do?

By calling Thread. currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.

What happens if the current thread has interrupted by another thread in thread interrupted exception?

In this state, a thread is waiting for a signal from another thread. When a thread either finishes execution or terminates abnormally, it'll wind up in the TERMINATED state. Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException.

What is thread interruption in Java?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.


1 Answers

interrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.

A common error is to call a static method on an instance.

Thread myThread = ...; if (myThread.interrupted()) {} // WRONG! This might not be checking myThread. if (myThread.isInterrupted()) {} // Right! 

Another difference is that interrupted() also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false even if the first call returned true.

The Javadocs tell you important things like this; use them often!

like image 200
Michael Myers Avatar answered Sep 20 '22 06:09

Michael Myers