Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread.sleep() implementation

Can someone help me understand how the Thread.sleep() function is implemented? A thread resumes/wakes up when the specified time elapses or when some other thread interrupts. I'm interested in understanding the design pattern behind the working of this.

Sleep is said to have no effect on the CPU consumption. Is the current thread added to a list of listeners? When will the check for interrupt flag occur? Does the scheduler keep checking for the interrupt status of every thread that is sleeping for every "x" amount of time (based on what the OS supports)? How does the thread get the control back without effecting the CPU.

I have searched for this. Sorry if I missed any link that is easy to find.

like image 692
Praneeth Avatar asked Dec 25 '12 00:12

Praneeth


1 Answers

Can someone help me understand how the Thread.sleep() function is implemented?

It calls sleep on the underlying native thread provided by the operating system.

Sleep is said to have no effect on the CPU consumption.

A thread that is not running does not consume CPU time.

Is the current thread added to a list of listeners?

No.

When will the check for interrupt flag occur?

The thread cannot check the interrupt flag because it is not running. The operating system can wake the thread if requested.

Does the scheduler keep checking for the interrupt status of every thread that is sleeping for every "x" amount of time (based on what the OS supports)?

No.

How does the thread get the control back without effecting the CPU.

The thread is automatically woken by the operating system when the time expires, or another thread can ask the operating system to wake it early.


Here is some of the code behind Thread.sleep() in OpenJVM:

 2811     ThreadState old_state = thread->osthread()->get_state();
 2812     thread->osthread()->set_state(SLEEPING);
 2813     if (os::sleep(thread, millis, true) == OS_INTRPT) {
 2814       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
 2815       // us while we were sleeping. We do not overwrite those.
 2816       if (!HAS_PENDING_EXCEPTION) {
 2817         HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
 2818         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
 2819         // to properly restore the thread state.  That's likely wrong.
 2820         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
 2821       }
 2822     }
 2823     thread->osthread()->set_state(old_state);
like image 180
Mark Byers Avatar answered Oct 02 '22 00:10

Mark Byers