9

Is FileLock in java safe across multiple threads within the same process or between different processes or both?

The javadoc says:

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

File-lock objects are safe for use by multiple concurrent threads.

which I don't really get: does it mean that FileLock is safe across multiple threads within the same single process, between multiple different processes or both?

1
  • What part of 'not suitable for controlling access to a file by multiple threads within the same virtual machine' didn't you get? It is perfectly clear.
    – user207421
    May 10, 2012 at 11:13

2 Answers 2

3

Further down:

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

This strongly suggests that its purpose is to be used between different processes.

This line:

They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

suggests you should not use it if you have a single process with multiple threads. In that case you can instead use a synchronized section or a ReadWriteLock.

2

It says that the objects are thread-safe when you look at them as plain Java objects, but that they won't stop other threads from opening the same file. That is, they are not safe when you look at the service they provide.

2
  • So in other words, it is safe for synchronization of files between processes but not for synchronization of files between threads of the same process?
    – shawn
    May 10, 2012 at 9:57
  • 1
    Yes, that's what the doc says. But there was a post recently where a guy still managed to use file locks inside Java. He wasn't relying on them to prevent opening by other threads, but as advisory locks -- you can explicitly try to acquire a file lock and see if you succeeded. Still, this is a dubious practice, with cross-platform hazards, and an obvious misuse of low-level file locks. May 10, 2012 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.