问题
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