9

From the java 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?

1
  • 1
    I believe native code for is open-source too,so you can just check what is going on there.
    – pajton
    Apr 26, 2010 at 2:58

3 Answers 3

7

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

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.

2
  • @Michael: I did a very crude testing. Basically just looping a few million times and in the loop calling isInterrupted() for the first test, and reading the variable for the second. No other threads involved. I also kept a reference to the value so the loop wouldn't be optimized away.
    – JRL
    Apr 25, 2010 at 13:04
  • 1
    Beware of micro-benchmarks! Especially on a JVM. There are many factors that can easily skew the results. The ideal thing to do is to implement this in your application and test it for real. More details at ibm.com/developerworks/java/library/j-jtp02225.html.
    – mdma
    Apr 27, 2010 at 10:46
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.