From the java sources, it look like to drops into native code. Is the cost roughly equivalent to a volatile read or does it need to acquire a lock of some type?
The isInterrupted() method of thread class is an instance method that tests whether the thread has been interrupted. It returns the value of the internal flag either true or false. If the thread is interrupted then it will return true otherwise false.
interrupted() method is a static method of class thread checks the current thread and clear the interruption "flag". i.e. a second call to interrupted() will return false. isInterrupted() method is an instance method; it reports the status of the thread on which it is invoked. it does not clear the interruption flag.
This method simply returns a flag that is set by the interrupt() method. The main difference between these two methods is that the interrupted() method resets the value of the flag to false. The isInterrupted() method does not change the value of the flag.
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.
Thread.isInterrupted()
is a very cheap function to call. There a few more indirections but all calls are quick enough. To summarize:
It must be possible for Java to emulate
Thread.currentThread().isInterrupted()
by performing the double indirectionThread::current()->_osthread->_interrupted
.
Source:
bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
assert(Thread::current() == thread || Threads_lock->owned_by_self(),
"possibility of dangling Thread pointer");
OSThread* osthread = thread->osthread();
bool interrupted = osthread->interrupted();
if (interrupted && clear_interrupted) {
osthread->set_interrupted(false);
// consider thread->_SleepEvent->reset() ... optional optimization
}
return interrupted;
}
OSThread
is implemented like this:
volatile jint _interrupted; // Thread.isInterrupted state
// Note: _interrupted must be jint, so that Java intrinsics can access it.
// The value stored there must be either 0 or 1. It must be possible
// for Java to emulate Thread.currentThread().isInterrupted() by performing
// the double indirection Thread::current()->_osthread->_interrupted.
....
volatile bool interrupted() const { return _interrupted != 0; }
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