Java file locking on a network

前端 未结 4 1409
执念已碎
执念已碎 2021-01-17 12:01

This is perhaps similar to previous posts, but I want to be specific about the use of locking on a network, rather than locally. I want to write a file to a shared location,

4条回答
  •  旧巷少年郎
    2021-01-17 12:53

    I found this bug report which describes why the note about file locking was added to the File.createNewFile documentation.

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4676183

    It states:

    If you mark the file as deleteOnExit before invoking createNewFile but the file already exists, you run the risk of deleting a file you didn't create and dropping someone elses lock! On the other hand, if you mark the file after creating it, you lose atomicity: if the program exits before the file is marked, it won't get deleted and the lock will be "wedged".

    So it looks like the main reason locking is discouraged with File.createNewFile() is that you can end up with orphaned lock files if the JVM unexpectedly terminates before you have a chance to delete it. If you can deal with orphaned lock files then it could be used as a simple locking mechanism. However, I wouldn't recommend the method suggested in the comments of the bug report as it has race conditions around read/writing the timestamp value and reclaiming the expired lock.

提交回复
热议问题