【问题标题】:What is the performance cost of calling Thread.isInterrupted()?调用 Thread.isInterrupted() 的性能成本是多少?
【发布时间】:2011-02-12 01:24:11
【问题描述】:

从 java 源代码来看,它看起来像是掉进了本机代码。成本大致相当于 volatile 读取还是需要获取某种类型的锁?

【问题讨论】:

  • 我相信本机代码也是开源的,所以你可以检查那里发生了什么。

标签: java performance multithreading


【解决方案1】:

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

Java 必须可以通过执行双重间接Thread::current()->_osthread->_interrupted 来模拟Thread.currentThread().isInterrupted()

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

【讨论】:

    【解决方案2】:

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

    link text

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • @Michael:我做了一个非常粗略的测试。基本上只是循环几百万次,并在循环中调用 isInterrupted() 进行第一次测试,并读取第二次的变量。不涉及其他线程。我还保留了对该值的引用,因此不会优化循环。
      • 小心微基准!特别是在 JVM 上。有许多因素很容易扭曲结果。理想的做法是在您的应用程序中实现它并进行真实测试。更多详情请访问ibm.com/developerworks/java/library/j-jtp02225.html
      猜你喜欢
      • 2010-09-20
      • 2018-02-16
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 2010-11-15
      • 2017-05-13
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多