Thread.sleep() problem

The following is a JUnit test that looks like it should always run without a problem. Mark the current time in a variable called start call Thread.sleep and tell it to sleep for x number of seconds, note the current time again in a variable called end and then assert that end - start is going to be less than or equal to x.


    public void testThreadSleep() throws Exception {
        long start = 0;
        long end = 0;
        long elapsedTime = 0;
        for(int i = 1000; i < 1500 ; i = i + 20){
            start = System.currentTimeMillis();
            Thread.sleep(i);
            end = System.currentTimeMillis();
            assertTrue(i <= end - start);
        }
    }

However in acutally running this code the assertion is not always true. It appears that when you try to call Thread.sleep(x) it may not sleep for the entire x milliseconds. Obviously it might take longer than x because a thread isn’t guaranteed to run. There might be another thread with a higher priority or the system might be doing garbage collection. However I would expect that it wouldn’t run less than the specified amount of time, but that is what appears to be happening.

I believe this has to do with the way that the JVM operates. Evidently it may wake up a thread a few milliseconds before the appointed time. It is possible that it may be anticipating garbage collection and waking threads up slightly early

About 

Leave a Reply

Your email address will not be published.