Is it possible that a file lock never gets released?

流过昼夜 提交于 2021-01-28 12:11:14

问题


Given the following file lock request:

FileLock lock = null;
try {
    lock = randomAccessFile.getChannel().lock(0, Long.MAX_VALUE, mode.shared);
    // work with file
} finally {
    if (lock != null) {
        lock.release();
    }
}

The targetted OS being MS Windows, is there any chance the finally block won't be ever executed, and thus the lock never released? For example, what if the JVM crashes? How to handle such a no-owner-lock?


回答1:


When the process exits, any OS automatically releases all resources acquired by the process, however there is no guarantee when this will happen.

In case of Windows Oracle JVM uses LockFileEx function as a native implementation and according to msdn https://msdn.microsoft.com/en-us/library/aa365202.aspx

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this is not done, access to these files may be denied if the operating system has not yet unlocked them.



来源:https://stackoverflow.com/questions/28900777/is-it-possible-that-a-file-lock-never-gets-released

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!