Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 调用Thread.isInterrupted()的性能成本是多少?_Java_Performance_Multithreading - Fatal编程技术网

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

Java 调用Thread.isInterrupted()的性能成本是多少?,java,performance,multithreading,Java,Performance,Multithreading,从java源代码来看,它看起来像是进入了本机代码。成本大致相当于易失性读取还是需要获取某种类型的锁?该方法用于检查线程是否中断,并且不会影响性能。如果线程已经中断,它也不会重置。 另请参见以下链接: 我不知道它是否获得锁,但我运行了一个快速测试,对我来说,isInterrupted()大约比读取一个volatile变量慢100倍。现在,我无法告诉您这在应用程序中是否重要。Thread.isInterrupted()是一个非常便宜的调用函数。还有一些间接操作,但所有调用都足够快。总结如下: Ja

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

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


我不知道它是否获得锁,但我运行了一个快速测试,对我来说,
isInterrupted()
大约比读取一个volatile变量慢100倍。现在,我无法告诉您这在应用程序中是否重要。

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

Java必须能够通过执行双间接方式来模拟
Thread.currentThread().isInterrupted()
,即
Thread::current()->\u osthread->\u interrupted

:

实现方式如下:

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

@迈克尔:我做了一个非常粗糙的测试。基本上只是循环几百万次,在循环中第一次调用isInterrupted(),第二次读取变量。没有涉及其他线程。我还保留了一个对值的引用,这样循环就不会被优化掉。小心微基准测试!尤其是在JVM上。有许多因素很容易影响结果。理想的做法是在应用程序中实现这一点,并对其进行实际测试。更多详细信息,请访问。我相信的本机代码也是开源的,所以您可以查看那里发生了什么。
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; }