ICR
ICR

Reputation: 14162

Will File.lastModified value always increase?

I'm trying to monitor a file for changes in Java running on either Windows or Linux.

Currently I am looking into polling the last-modified property of the file instead of hooking into OS file events in an attempt to avoid dealing with smoothing over the API differences and handling asynchronous events.

I'm storing the result of new File("path").lastModified() once I've processed the file and comparing new lastModified results every x seconds.

Can I rely on the fact that, assuming no foul play and someone manually modifying the timestamp, lastModified will always increase? The Java docs say that it is an offset from a GMT epoch, so presumably it won't go backwards even with timezone adjustments?

Upvotes: 4

Views: 1277

Answers (2)

npe
npe

Reputation: 15709

Well, sometimes, lastModified does not increase. It is all about time resolution and the resolution is different in each file system:

  • all FATs (FAT32, FAT16, FAT12) have a 2 second time resolution,
  • for NTFS it is 100 ns (yep, nanoseconds)
  • for most *nixes its 1 second.

So, if your files will change rapidly, lastModified will not change, and your monitor may lose some changes.

This is also very tricky, because if you have the same file on different filesystems (like FAT32 and NTFS) their lastModified time will differ due to different time resolution. Now because ot that, you may be reacting to fake file changes that did not happen - it's just the FAT32 returning a time that is 1 second different than the NTFS time. This is also the case with web servers - if you don't know the server file system, then you don't know what the time resolution of the value in a HTTP Header is.

The workaround is to assume, that the file did not change if the difference between stored value, and FS value is less than 3-4 seconds. That's what WebStart does when checking for new versions of JAR files on the server.

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can change the timestamp of a file to anything

http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If time is corrected using something like NTP, it can go backwards.

These situations are rare, and it might not be something you need to worry about.

Upvotes: 1

Related Questions