A developer sought yesterday some advice about the best way to implement the following feature in his application : how to react, as quickly as possible, to the creation of a special "lock file" in a well-known directory.
His current implementation uses a polling thread calling the File.exists()
method every few hundreds ms, which is a best-effort tradeoff between notification speed and unnecessary CPU burning.
As of Java 7, there is a better way to achieve this.
The java.nio.file
package provides a WatchService
that plugs directly into the underlying OS's file notification system, allowing the application to be asychronously notified of filesystem-related events of certain types (file creation, modification, deletion, etc.).
This WatchService
works alot like the dreaded NIO channel Selector
, but is fortunately simpler : first declare which events you are interested in, then loop on a blocking method to wait for some event to occur, process it as required, rince and repeat.
Here is what I quickly coded as a proof-of-concept.