What is the performance cost of calling Thread.isInterrupted()?
From the java 开发者_Go百科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?
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; }
The method isInterrupted
is used to checks whether the Thread is interrupted or not and it does not affect the performance. Also it does not reset, if thread was already interrupted.
Also See the following links:
link text
link text
I don't know whether it acquires a lock or not but I ran a quick test and for me isInterrupted()
is roughly 100 times slower than reading a volatile variable. Now whether that would matter or not in your application, I can't tell you.
精彩评论