从Java源代码来看,它似乎会转换为本地代码。它的成本是否大致相当于volatile读取,还是需要获取某种类型的锁定?
从Java源代码来看,它似乎会转换为本地代码。它的成本是否大致相当于volatile读取,还是需要获取某种类型的锁定?
Thread.isInterrupted()
是一个非常便宜的函数调用。虽然有一些额外的间接调用,但所有的调用都足够快速。总结一下:
Java必须通过执行双重间接调用
Thread::current()->_osthread->_interrupted
来模拟Thread.currentThread().isInterrupted()
。
来源:
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
是这样实现的:
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; }
我不知道它是否获取了锁,但我进行了快速测试,对我来说isInterrupted()
比读取易失性变量慢大约100倍。现在,无论在您的应用程序中是否重要,我不能告诉您。