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

David Holmes davidcholmes at aapt.net.au
Tue Nov 21 20:15:05 EST 2017


What were you expecting to “go to a spin loop generating random numbers for 300ms then go to the OS” ???

 

Thread.sleep parks the thread for around the time specified (modulo OS quirks mainly on windows).

 

scheduleAtFixedRate triggers a periodic release of a task. scheduleAtFixedDelay spaces releases of a task by a fixed interval.

 

David

 

From: Concurrency-interest [mailto:concurrency-interest-bounces at cs.oswego.edu] On Behalf Of Edward Sargisson via Concurrency-interest
Sent: Wednesday, November 22, 2017 10:52 AM
To: concurrency-interest at cs.oswego.edu
Subject: [concurrency-interest] Any advantage to ScheduledExecutorService.scheduleAtFixedRate vs Thread.sleep polling

 

Hi,

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 <http://cs.oswego.edu>  appears to be down)

 

The code is of the form:

while (!shutdown) {

  if( System.currentTimeMillis() - lastCheck > waitTime) {

    // do important stuff

   lastCheck = System.currentTimeMills()

  }

 Thread.sleep(1000);

}

 

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

finishLatch.await();

 

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 too.

 

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.

 

Cheers,

Edward

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20171122/1c91cc90/attachment.html>


More information about the Concurrency-interest mailing list