tags:

views:

66

answers:

4

I'm running some test to prove a concept and i just wrote this code and found a weird situation:

public class Test {

public static void main(String[] args) {

    Date now = new Date();

    File file = new File("/root/batch-experiments/test.txt");

    try {
        file.createNewFile();
    } catch (IOException e) {
        System.out.println("cannot create file...");
    }

    System.out.println(MessageFormat.format("Checking File {0}! Last Modified time is {1}. Must be newer than {2}", file.getName(),
            file.lastModified(), now.getTime()));

    if (file.lastModified() >= now.getTime()) {
        //ignore...
    } else {
        System.out.println(MessageFormat.format("File {0} is out of date and was ignored.", file));
    }
}

}

The output is:

Checking File test.txt! Last Modified time is 1,253,187,650,000. Must be newer than 1,253,187,650,496
File /root/batch-experiments/test.txt is out of date and was ignored.

How it is possible? Shouldn't be the file modified time after the new Date time? This is happening 1 in 4/5 tries.

What i'm missing in here?

Any way to guarantee that new Date() is older than file creation?

A: 

Maybe the compiler reordered the way the instructions are executed?

Perhaps, if your real intentions don't need of a millisecond or higher precision, a more accurate test should include some sleep time between both instructions.

Gothmog
+4  A: 

The file system date granularity is usually of one second (depending on the actual file system, it may also be worse). when you create the file, the creation time gets rounded.

Omry
+2  A: 

Granularity of last modified is probably less than milliseconds.

Zed
+2  A: 

I know that Date object give the milliseconds, but only every 15.5 ms on our machines. Specifically, in our log module, we see delta between dates that are : 15ms, 16ms, 31ms, 47ms ...

This could explain at least a 15ms difference.


Apart from that, in my experience, file operations shouldn't rely too much on precise dates. I have seen many implementations of dependency or up-to-date checkers that have a tolerance of around 300ms to 2s (and more for distant files). So they consider that a dependent file is up-to-date if it is posterior to, or anterior (but no more than 300ms).

KLE