java – 调用Thread.isInterrupted()的性能成本是多少?

java代码来看,它看起来像是本机代码.成本大致相当于易失性读取还是需要获取某种类型的锁定?

解决方法

Thread.isInterrupted()是一个非常便宜的函数.有一些更多的间接,但所有电话都足够快.总结一下:

It must be possible for Java to emulate Thread.currentThread().isInterrupted() by performing the double indirection Thread::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实现如下:

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; }

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...