Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 291
shawn Avatar asked May 10 '12 09:05

shawn


1 Answers

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.

like image 173
Tudor Avatar answered Nov 15 '22 14:11

Tudor