gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:26:35 25 4
gpt4 key购买 nike

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

最佳答案

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

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是这样实现的:

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

关于java - 调用 Thread.isInterrupted() 的性能成本是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com