tags:

views:

1276

answers:

3

Hello, I plan my java program to read a file which can be locked by another program to write into it so I need to check if the file is locked, if so wait until it is free and execute X function when free. How to achieve this?

ps: the enviroment that my java program will run will be a Windows 2000 server

A: 

Use a FileLock in all the Java applications using that file and have them run within the same JVM. Otherwise, this can't be done reliably.

Ben S
+1  A: 

If multiple processes (which can be a mix of Java and non-Java) might be using the file, use a FileLock. A key to using file locks successfully is to remember that they are only "advisory". The lock is guaranteed to be visible if you check for it, but it won't stop you from doing things to the file if you forget. All processes that access the file should be designed to use the locking protocol.

erickson
A: 

Under Windows with Sun's JVM, the FileLocks should work properly, although the JavaDocs leave the reliability rather vague (system dependent).

Nevertheless, if you only have to recognize in your Java program, that some other program is locking the file, you don't have to struggle with FileLocks, but can simply try to write to the file, which will fail if it is locked. You better try this on your actual system, but I see the following behaviour:

File f = new File("some-locked-file.txt");
System.out.println(f.canWrite()); // -> true
new FileOutputStream(f); // -> throws a FileNotFoundException

This is rather odd, but if you don't count platform independence too high and your system shows the same behaviour, you can put this together in a utility function.

With current Java versions, there is unfortunately no way to be informed about file state changes, so if you need to wait until the file can be written, you have to try every now and then to check if the other process has released its lock. I'm not sure, but with Java 7, it might be possible to use the new WatchService to be informed about such changes.

jarnbjo