物业:
我试图在静态函数中锁定一个文件,该函数返回一个包含通道和锁的组合对象,因此另一个函数unlockFile(FileLocking fl)可用于关闭然后通道并释放锁。组合对象类如下所示: `
public class FileLocking {
public FileChannel channel;
public FileLock lock;
public FileLocking(FileChannel f, FileLock l) {
channel = f;
lock = l;
}
锁定文件的函数如下所示:
public static synchronized FileLocking lockFile(String fileName) {
FileLocking result = null;
FileChannel channel = null;
try {
channel = new FileOutputStream(fileName).getChannel();
FileLock lock = channel.lock();
lock = channel.tryLock();
result = new FileLocking(channel, lock);
} catch (Exception e) {
Log(ERR, "Exception when locking " + e.getMessage());
e.printStackTrace();
} finally {
try {
channel.close();
} catch (IOException e) {
Log(ERR, "IOE: " + e.getMessage());
e.printStackTrace();
}
}
return result;
}
目前,我收到以下错误:
[ERR]: (pid:13) Exception when locking null
java.nio.channels.OverlappingFileLockException
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(Unknown Source)
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(Unknown Source)
at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
at java.nio.channels.FileChannel.tryLock(Unknown Source)
at com.xxx.utils.FileLocking.lockFile(FileLocking.java:29)`
非常感谢解释和/或编码技术。
答案 0 :(得分:8)
为什么在tryLock
之后再次致电lock
?我错过了什么吗?
你得到OverlappingFileLockException,因为当你第二次调用tryLock
时,JVM已经拥有了锁。