Java文件锁定

Java文件锁定,java,file-io,locking,Java,File Io,Locking,我已经编写了下面的helper类,它应该允许我获得一个文件的独占锁,然后用它做一些事情 public abstract class LockedFileOperation { public void execute(File file) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath());

我已经编写了下面的helper类,它应该允许我获得一个文件的独占锁,然后用它做一些事情

public abstract class LockedFileOperation {

    public void execute(File file) throws IOException {

        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        // Get an exclusive lock on the whole file
        FileLock lock = channel.lock();
        try {
            lock = channel.lock();
            doWithLockedFile(file);
        } finally {
            lock.release();
        }
    }

    public abstract void doWithLockedFile(File file) throws IOException;
}
下面是我编写的一个单元测试,它创建了LockedFileOperation的一个子类,试图重命名锁定的文件

public void testFileLocking() throws Exception {

    File file = new File("C:/Temp/foo/bar.txt");
    final File newFile = new File("C:/Temp/foo/bar2.txt");

    new LockedFileOperation() {

        @Override
        public void doWithLockedFile(File file) throws IOException {
            if (!file.renameTo(newFile)) {
                throw new IOException("Failed to rename " + file + " to " + newFile);
            }
        }
    }.execute(file);
}
当我运行此测试时,调用channel.lock时会引发OverlappingFileLockException。我不清楚为什么会发生这种情况,因为我只尝试锁定此文件一次

在任何情况下,lock方法的JavaDocs都会说:

调用此方法将 阻塞,直到可以锁定区域, 此频道已关闭,或者 调用线程被中断, 以先到者为准

因此,即使文件已经锁定,lock方法似乎也应该阻塞,而不是抛出OverlappingFileLockException

我想我误解了FileLock的一些基本特性。我在Windows XP上运行,以防与此相关

谢谢,
不要

您锁定了两次文件,并且从未释放第一次锁定:

    // Get an exclusive lock on the whole file
    FileLock lock = channel.lock();
    try {
        lock = channel.lock();
        doWithLockedFile(file);
    } finally {
        lock.release();
    }
在重用var锁时,在哪里释放第一个

您的代码应该是:

    // Get an exclusive lock on the whole file
    FileLock lock = null;
    try {
        lock = channel.lock();
        doWithLockedFile(file);
    } finally {
        if(lock!=null) {
           lock.release();
         }
    }

您锁定了两次文件,但从未释放第一个锁:

    // Get an exclusive lock on the whole file
    FileLock lock = channel.lock();
    try {
        lock = channel.lock();
        doWithLockedFile(file);
    } finally {
        lock.release();
    }
在重用var锁时,在哪里释放第一个

您的代码应该是:

    // Get an exclusive lock on the whole file
    FileLock lock = null;
    try {
        lock = channel.lock();
        doWithLockedFile(file);
    } finally {
        if(lock!=null) {
           lock.release();
         }
    }