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

时间:2010-04-25 09:12:06

标签: java performance multithreading

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

3 个答案:

答案 0 :(得分:5)

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

  

Java必须能够通过执行双重间接Thread.currentThread().isInterrupted()来模拟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; }

答案 1 :(得分:1)

我不知道它是否获得了锁定,但是我进行了快速测试,对我而言isInterrupted()比读取volatile变量慢大约100倍。现在,无论你的申请中是否重要,我都无法告诉你。

答案 2 :(得分:0)

方法isInterrupted用于检查线程是否被中断,并且不会影响性能。如果线程已被中断,它也不会重置。 另请参阅以下链接: link text

link text