Why does Java Thread.sleep or Date.after () work differently on other computers?

I have a unit test that checks that an object inside my instance has been instantiated with an appropriate Date position:

    Date earlier = new Date();
    Thread.sleep(10);
    instance.execute();
    assertTrue(instance.getMyObject.getCreationDate().after(earlier));

      

This test works for me on Windows 7 Java 6 when running in Eclipse or using Ant from the command line. However, my client says that this test is failing for him (he did not specify his environment). How could this be?

+3


source to share


3 answers


In Windows XP, the clock resolution is only 1/60 of a second. This means you can wait 10ms and the clock will display the same. I would increase the time to 100-250ms.



+8


source


System.currentTimeMillis has a different "resolution" on different platforms. On Windows, this might be 15ms - that would mean that your 10ms of wait might not necessarily lead to a "later" date.



I would increase Thread.sleep(10)

to Thread.sleep(100)

or more.

+3


source


As Peter Laurie replied, the system clock permission may mean it hasn't updated between your "earlier" date and instance date being created. Maybe change your code to the following:

assertFalse(instance.getMyObject.getCreationDate().before(earlier));

      

This way, you check that it is definitely not earlier than your earlier date, and you do not need to worry about whether the system clock is updated or not.

+1


source







All Articles