jvm原始碼分析之yield和sleep
概述
由於Thread的yield和sleep有一定的相似性,因此放在一起進行分析。yield會釋放CPU資源,讓優先順序更高(至少是相同)的執行緒獲得執行機會;sleep當傳入引數為0時,和yield相同;當傳入引數大於0時,也是釋放CPU資源,當可以讓其它任何優先順序的執行緒獲得執行機會;
假設當前程序只有main執行緒,當呼叫yield之後,main執行緒會繼續執行,因為沒有比它優先順序更高的執行緒;而呼叫sleep之後,mian執行緒會進入TIMED_WAITING狀態,不會繼續執行;
yield
Thread.yield底層是通過JVM_Yield方法實現的(見jvm.cpp):
JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass)) JVMWrapper("JVM_Yield"); //檢查是否設定了DontYieldALot引數,預設為fasle //如果設定為true,直接返回 if (os::dont_yield()) return; //如果ConvertYieldToSleep=true(預設為false),呼叫os::sleep,否則呼叫os::yield if (ConvertYieldToSleep) { os::sleep(thread, MinSleepInterval, false);//sleep 1ms } else { os::yield(); } JVM_END
從上面知道,實際上呼叫的是os::yield:
//sched_yield是linux kernel提供的API,它會使呼叫執行緒放棄CPU使用權,加入到同等優先順序佇列的末尾;
//如果呼叫執行緒是優先順序最高的唯一執行緒,yield方法返回後,呼叫執行緒會繼續執行;
//因此可以知道,對於和呼叫執行緒相同或更高優先順序的執行緒來說,yield方法會給予了它們一次執行的機會;
void os::yield() {
sched_yield();
}
sched_yield()的man手冊描述如下:
DESCRIPTION
sched_yield() causes the calling thread to relinquish the CPU. The thread is moved to the end of the queue for its static priority and a new thread gets to run.
RETURN VALUE
On success, sched_yield() returns 0. On error, -1 is returned, and errno is set appropriately.
ERRORS
In the Linux implementation, sched_yield() always succeeds.
翻譯一下,sched_yield()會讓出當前執行緒的CPU佔有權,然後把執行緒放到靜態優先佇列的尾端,然後一個新的執行緒會佔用CPU。
sched_yield()這個函式可以使用另一個級別等於或高於當前執行緒的執行緒先執行。如果沒有符合條件的執行緒,那麼這個函式將會立刻返回然後繼續執行當前執行緒的程式。
sleep
Thread.sleep最終呼叫JVM_Sleep方法:
JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis)) JVMWrapper("JVM_Sleep"); if (millis < 0) {//引數校驗 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); } //如果執行緒已經中斷,丟擲中斷異常,關於中斷的實現,在另一篇文章中會講解 if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) { THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted"); } //設定執行緒狀態為SLEEPING JavaThreadSleepState jtss(thread); EventThreadSleep event; if (millis == 0) { //如果設定了ConvertSleepToYield(預設為true),和yield效果相同 if (ConvertSleepToYield) { os::yield(); } else {//否則呼叫os::sleep方法 ThreadState old_state = thread->osthread()->get_state(); thread->osthread()->set_state(SLEEPING); os::sleep(thread, MinSleepInterval, false);//sleep 1ms thread->osthread()->set_state(old_state); } } else {//引數大於0 //儲存初始狀態,返回時恢復原狀態 ThreadState old_state = thread->osthread()->get_state(); //osthread->thread status mapping: // NEW->NEW //RUNNABLE->RUNNABLE //BLOCKED_ON_MONITOR_ENTER->BLOCKED //IN_OBJECT_WAIT,PARKED->WAITING //SLEEPING,IN_OBJECT_WAIT_TIMED,PARKED_TIMED->TIMED_WAITING / //TERMINATED->TERMINATED thread->osthread()->set_state(SLEEPING); //呼叫os::sleep方法,如果發生中斷,丟擲異常 if (os::sleep(thread, millis, true) == OS_INTRPT) { if (!HAS_PENDING_EXCEPTION) { if (event.should_commit()) { event.set_time(millis); event.commit(); } THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted"); } } thread->osthread()->set_state(old_state);//恢復osThread狀態 } if (event.should_commit()) { event.set_time(millis); event.commit(); } JVM_END
os::sleep的原始碼如下:
int os::sleep(Thread* thread, jlong millis, bool interruptible) {
assert(thread == Thread::current(), "thread consistency check");
//執行緒有如下幾個成員變數:
//ParkEvent * _ParkEvent ; // for synchronized()
//ParkEvent * _SleepEvent ; // for Thread.sleep
//ParkEvent * _MutexEvent ; // for native internal Mutex/Monitor
//ParkEvent * _MuxEvent ; // for low-level muxAcquire-muxRelease
ParkEvent * const slp = thread->_SleepEvent ;
slp->reset() ;
OrderAccess::fence() ;
//如果millis>0,傳入interruptible=true,否則為false
if (interruptible) {
jlong prevtime = javaTimeNanos();
for (;;) {
if (os::is_interrupted(thread, true)) {//判斷是否中斷
return OS_INTRPT;
}
jlong newtime = javaTimeNanos();//獲取當前時間
//如果linux不支援monotonic lock,有可能出現newtime<prevtime
if (newtime - prevtime < 0) {
assert(!Linux::supports_monotonic_clock(), "time moving backwards");
} else {
millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
}
if(millis <= 0) {
return OS_OK;
}
prevtime = newtime;
{
assert(thread->is_Java_thread(), "sanity check");
JavaThread *jt = (JavaThread *) thread;
ThreadBlockInVM tbivm(jt);
OSThreadWaitState osts(jt->osthread(), false );
jt->set_suspend_equivalent();
slp->park(millis);
jt->check_and_wait_while_suspended();
}
}
} else {
//如果interruptible=false //設定osthread的狀態為CONDVAR_WAIT
OSThreadWaitState osts(thread->osthread(), false );
jlong prevtime = javaTimeNanos();
for (;;) {
jlong newtime = javaTimeNanos();
if (newtime - prevtime < 0) {
assert(!Linux::supports_monotonic_clock(), "time moving backwards");
} else {
millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
}
if(millis <= 0) break ;
prevtime = newtime;
slp->park(millis);//底層呼叫pthread_cond_timedwait實現
}
return OS_OK ;
}
park(jlong millis)原始碼如下:
int os::PlatformEvent::park(jlong millis) {
guarantee (_nParked == 0, "invariant") ;
int v ;
for (;;) {
v = _Event ;
if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
}
guarantee (v >= 0, "invariant") ;
if (v != 0) return OS_OK ;
// We do this the hard way, by blocking the thread.
// Consider enforcing a minimum timeout value.
struct timespec abst;
compute_abstime(&abst, millis);
int ret = OS_TIMEOUT;
int status = pthread_mutex_lock(_mutex);
assert_status(status == 0, status, "mutex_lock");
guarantee (_nParked == 0, "invariant") ;
++_nParked ;
// Object.wait(timo) will return because of
// (a) notification
// (b) timeout
// (c) thread.interrupt
//
// Thread.interrupt and object.notify{All} both call Event::set.
// That is, we treat thread.interrupt as a special case of notification.
// The underlying Solaris implementation, cond_timedwait, admits
// spurious/premature wakeups, but the JLS/JVM spec prevents the
// JVM from making those visible to Java code. As such, we must
// filter out spurious wakeups. We assume all ETIME returns are valid.
//
// TODO: properly differentiate simultaneous notify+interrupt.
// In that case, we should propagate the notify to another waiter.
while (_Event < 0) {
status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
if (status != 0 && WorkAroundNPTLTimedWaitHang) {
pthread_cond_destroy (_cond);
pthread_cond_init (_cond, os::Linux::condAttr()) ;
}
assert_status(status == 0 || status == EINTR ||
status == ETIME || status == ETIMEDOUT,
status, "cond_timedwait");
if (!FilterSpuriousWakeups) break ; // previous semantics
if (status == ETIME || status == ETIMEDOUT) break ;
// We consume and ignore EINTR and spurious wakeups.
}
--_nParked ;
if (_Event >= 0) {
ret = OS_OK;
}
_Event = 0 ;
status = pthread_mutex_unlock(_mutex);
assert_status(status == 0, status, "mutex_unlock");
assert (_nParked == 0, "invariant") ;
// Paranoia to ensure our locked and lock-free paths interact
// correctly with each other.
OrderAccess::fence();
return ret;
}
通過閱讀原始碼知道,原來sleep是通過pthread_cond_timedwait實現的,那麼為什麼不通過linux的sleep實現呢?
- pthread_cond_timedwait既可以堵塞在某個條件變數上,也可以設定超時時間;
- sleep不能及時喚醒執行緒,最小精度為秒;
可以看出pthread_cond_timedwait使用靈活,而且時間精度更高;
# 例子
通過strace可以檢視程式碼的系統呼叫情況,建立兩個類,一個呼叫Thread.sleep(),一個呼叫Thread.yield(),檢視其系統呼叫情況:
- Thread.yield
Thread.yield();
System.out.println("hello");
.yield();
System.out.println("hello");
上圖可以看到sched_yield的系統呼叫
- Thread.sleep(nonzero)
Thread.sleep(1000);
System.out.println("hello");
在其中並沒有看到pthread_cond_timedwait的呼叫,其實Java的執行緒有可兩種實現方式:
- LinuxThreads
- NPTL(Native POSIX Thread Library)
// NPTL or LinuxThreads?
static bool is_LinuxThreads() { return !_is_NPTL; }
static bool is_NPTL() { return _is_NPTL; }
可以通過如下命令檢視到底是使用哪種執行緒實現:
getconf GNU_LIBPTHREAD_VERSION
關於兩者之間的區別,請檢視wiki。由於我的機器上採用的是2,因此無法看到ppthread_cond_timedwait的呼叫;
ppthread_cond_timedwait採用futex(Fast Userspace muTEXes)實現,因而可以看到對futex的呼叫;
關於JVM是如何決定採用哪種實現方式,可以檢視如下方法(os_linux.cpp):
// detecting pthread library
void os::Linux::libpthread_init() {
// Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
// and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
// generic name for earlier versions.
// Define macros here so we can build HotSpot on old systems.
# ifndef _CS_GNU_LIBC_VERSION
# define _CS_GNU_LIBC_VERSION 2
# endif
# ifndef _CS_GNU_LIBPTHREAD_VERSION
# define _CS_GNU_LIBPTHREAD_VERSION 3
# endif
size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
if (n > 0) {
char *str = (char *)malloc(n, mtInternal);
confstr(_CS_GNU_LIBC_VERSION, str, n);
os::Linux::set_glibc_version(str);
} else {
// _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
static char _gnu_libc_version[32];
jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release());
os::Linux::set_glibc_version(_gnu_libc_version);
}
//系統函式confstr獲取C庫資訊
n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
if (n > 0) {
char *str = (char *)malloc(n, mtInternal);
confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
// Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
// us "NPTL-0.29" even we are running with LinuxThreads. Check if this
// is the case. LinuxThreads has a hard limit on max number of threads.
// So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
// On the other hand, NPTL does not have such a limit, sysconf()
// will return -1 and errno is not changed. Check if it is really NPTL.
if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 && strstr(str, "NPTL") && sysconf(_SC_THREAD_THREADS_MAX) > 0) {
free(str);
os::Linux::set_libpthread_version("linuxthreads");
} else {
os::Linux::set_libpthread_version(str);
}
} else {
// glibc before 2.3.2 only has LinuxThreads.
os::Linux::set_libpthread_version("linuxthreads");
}
if (strstr(libpthread_version(), "NPTL")) {
os::Linux::set_is_NPTL();
} else {
os::Linux::set_is_LinuxThreads();
}
// LinuxThreads have two flavors: floating-stack mode, which allows variable // stack size; and fixed-stack mode. NPTL is always floating-stack.
if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) {
os::Linux::set_is_floating_stack();
}