I want to exclusively lock text file from Java code, so I found following example:
public class Main
{
public static void main(String args[]) throws IOException
{
String strFilePath = "M:/Projects/SafeFile/ClientSide/dump/data6.txt";
writeFileWithLock(new File(strFilePath), "some_content");
}
public static void writeFileWithLock(File file, String content) {
// auto close and release the lock
try (RandomAccessFile reader = new RandomAccessFile(file, "rw");
FileLock lock = reader.getChannel().lock()) {
// Simulate a 10s locked
TimeUnit.SECONDS.sleep(10);
reader.write(content.getBytes());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
When I double click on data6.txt before 10 seconds elapse, my expectation is that I will receive some message like "File already opened by other process" or something similar. But I manage to open it without any problems. Does anybody see what is wrong with this code? Thanks!
FileLock does not generally use mandatory locks. This means that FileLock will generally provide locking only against other applications that use FileLock or equivalent.
Depending on the OS, there may be different system calls to lock files. For example fcntl or lockf.
To summarize, you may not safely assume that FileLock is a mandatory lock in every platform.