[concurrency-interest] Any advantage to ScheduledExecutorService.scheduleAtFixedRate vs Thread.sleep polling

Edward Sargisson esarge at pobox.com
Tue Nov 21 19:51:37 EST 2017

I'm curious about this because I discussed this with my boss and then
tested some code and got a result I didn't expect. My expectation was that
polling with Thread.sleep every second would keep a core 30% busy (because
it would go to a spin loop generating random numbers for 300ms and then go
to the OS). However, my test doesn't show this.

I'm hoping the collective expertise on this list might provide some useful
information for others who come along with similar questions. (And
hopefully this email actually goes out because cs.oswego.edu appears to be

The code is of the form:
while (!shutdown) {
  if( System.currentTimeMillis() - lastCheck > waitTime) {
    // do important stuff
   lastCheck = System.currentTimeMills()

I proposed that using
ScheduledExecutorService.scheduleAtFixedRate(waitTime) would use less CPU
time because it wouldn't have to wake up only to see it had nothing to do
yet and go back to sleep. Based on Doug Lea's PhillyETE 2013 talk I was
expecting it to generate random numbers for a while.

I wrote a test that was essentially:
// start the thread above
scheduler.schedule(() -> finishLatch.countDown(), 5, TimeUnit.MINUTES);

I fired it up on macOS and attached YourKit to it.

The thing is sitting on 0% CPU!

I attempted to verify the result using the macOS Activity Monitor and the
process is showing ~0.3% CPU.

I gave Java Flight Recorder a run to see if it would show anything (my
first time using this tool). From what I can see it's registering 0% CPU

So, does Thread.sleep() actually sleep or is there something going on that
I don't know how to measure.

Many, many thanks in advance.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20171121/5ced0c3f/attachment.html>

More information about the Concurrency-interest mailing list