Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the performance cost of calling Thread.isInterrupted()?

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?

like image 919
Michael Barker Avatar asked Apr 25 '10 09:04

Michael Barker


People also ask

What is isInterrupted?

The isInterrupted() method of thread class is an instance method that tests whether the thread has been interrupted. It returns the value of the internal flag either true or false. If the thread is interrupted then it will return true otherwise false.

What is the difference between the interrupted () and isInterrupted () method in Java?

interrupted() method is a static method of class thread checks the current thread and clear the interruption "flag". i.e. a second call to interrupted() will return false. isInterrupted() method is an instance method; it reports the status of the thread on which it is invoked. it does not clear the interruption flag.

What is the difference between Isinterrupt method and interrupted method?

This method simply returns a flag that is set by the interrupt() method. The main difference between these two methods is that the interrupted() method resets the value of the flag to false. The isInterrupted() method does not change the value of the flag.

What is interrupted method in Java?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.


1 Answers

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; }
like image 143
bestsss Avatar answered Oct 24 '22 15:10

bestsss