I am running some JUnit tests on a single thread and they are failing in a non-deterministic way. I had one person tell me that the optimizing JVM (Oracle Hotspot 64-Bit 17.1-b03) is executing the instructions out of order for speed. I have trouble believing that the java spec would allow that, but I can't find the specific reference.
Wikipedia states that a single thread must enforce within-thread as-if-serial so I shouldn't have to worry about execution order differing from what I wrote. http://en.wikipedia.org/wiki/Java_Memory_Model#The_memory_model
Example code:
@Test
public void testPersistence() throws Exception
{
// Setup
final long preTestTimeStamp = System.currentTimeMillis();
// Test
persistenceMethod();
// Validate
final long postTestTimeStamp = System.currentTimeMillis();
final long updateTimeStamp = -- load the timestamp from the database -- ;
assertTrue("Updated time should be after the pretest time", updateTimeStamp >= preTestTimeStamp);
assertTrue("Updated time should be before the posttest time", updateTimeStamp <= postTestTimeStamp);
}
void persistenceMethod()
{
...
final long updateTime = System.currentTimeMillis();
...
-- persist updateTime to the database --
...
}
When this test code is run it has completely non-deterministic behavior, sometimes it passes, sometimes if fails on the first assert, and sometimes it fails on the second assert. The values are always within a millisecond or two of each other so it isn't that the persistence is just failing completely. Adding a Thread.sleep(2); between each statement does decrease the number of times the test fails, but doesn't eliminate the failures completely.
Is it possible that this is the fault of the JVM or is it more likely that the database (MsSql) is doing some sort of rounding of the stored data?