0

I read this post. Can anybody tell me if the java.nio.FileLock.lock() works well with java.util.Properties class.

Question:

If I put the lock on the properties file what I read, does this lock the file for other concurrent locking? The code Will lock something like:



try {

     Properties prop = new Properties();
     FileInputStream fis = new FileInputStream(new File("/my/path"));
     FileLock lock = fis.getChannel().lock();
     prop.load(fis);

} catch (FileNotFoundException e) {
   //catch it...
} catch (IOException e) {
   //catch it...
}

//....
lock.release();
//...

Thanks!


From JavaDocs:

1.The locks held on a particular file by a single Java virtual machine do not overlap.

and

2.a.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.

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

Related to 1: I tried to lock on the same file from the same JVM but from different threads, and it throws errors when a thread tried to put lock on the already locked file. I think that behavior is not how expected from the JavaDoc specifications.

Related to 2 a and b: It seems to me that they're contradicting. Am I right? If not, can anyone explain me what's the point?

Community
  • 1
  • 1
artaxerxe
  • 6,281
  • 21
  • 68
  • 106

1 Answers1

2

File locks are generally advisory: that is, they only affect other processes, e.g. JVMs, that are also using file locks. java.util.Properties doesn't do that at all, but then it doesn't process files either, only input streams. So if you provide the input streams from files that you are setting/checking file locks on, it will work. But only between JVMs, not within a single JVM: see the Javadoc.

user207421
  • 305,947
  • 44
  • 307
  • 483