2010-10-26 77 views
1

我已經編寫了下面的幫助類,它應該允許我在文件上獲得排它鎖,然後對其執行某些操作。Java文件鎖定

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()方法的JavaDoc說:

此方法的調用將 塊直到該區域可以被鎖定, 此通道被關閉時,或 調用線程是中斷, 以先到者爲準。

所以,即使文件已被鎖定似乎lock()方法應該阻止,而不是拋出OverlappingFileLockException

我想有一些基本的關於FileLock,我誤解了。我在Windows XP上運行(如果相關)。

謝謝, 唐

回答

6

您鎖定兩次文件,從不釋放第一鎖定:當你重複使用VAR鎖,你在哪裏釋放第一

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

你的代碼應該是:

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

哇,這是尷尬的,謝謝! – 2010-10-26 10:46:26