I got an interesting "time-travel" problem today, using the following code:
for (int i = 0; i < 1; i++){
long start = System.currentTimeMillis();
// Some code here
System.out.print(i + "\t" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
// Some code here
System.out.println("\t" + (System.currentTimeMillis() - start));
}
And I got the result
0 15 -606
And it seems that it is not repeatable. Anyone has any clues on what happened inside during the running time? Just curious...
New edit: I used a small test to confirmed the answers below. I run the program and change the system time during the run, and finally repeat the "time-travel":
0 -3563323 163
Case closed. Thanks guys!
More words: both currentTimeMillis() and nanoTime() are system-timer based, so they will be not monotonic if the system timer is updated (turned back, specifically). It is better to use some internet-based timer for such cases.