2013-10-25 60 views
1

我想保護我的代碼不會同時在一個目錄中做同樣的事情,而且我需要一種跨進程互斥體。由於有問題的目錄最終可能會在整個網絡上共享,我通過打開一個文件來寫作這種鎖。爲什麼我可以打開同一個文件在java中寫兩次

public static void main(String[] args) throws IOException { 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    try { 
     FileOutputStream fos = new FileOutputStream("lockfile", false); 
     try { 
      System.out.println("Lock obtained. Enter to exit"); 
      br.readLine(); 
      System.out.println("Done"); 
     } 
     finally { 
      fos.close(); 
     } 
    } catch (FileNotFoundException ex) { 
     System.out.println("No luck - file locked."); 
    } 
} 

運行java -jar dist\LockFileTest.jar兩次成功! - 我看到兩個控制檯提示Enter。

我也嘗試過new RandomAccessFile("lockfile", "rw")代替,效果相同。

背景:windows xp,32bit,jre1.5。

我的錯誤在哪裏?這怎麼可能?

+1

而不是打開該文件,您可以創建該文件以獲取鎖定並刪除該文件釋放它。 – DaoWen

回答

2

你試過FileLock嗎?

RandomAccessFile randomAccessFile = new RandomAccessFile("lockfile", "rw"); 
FileChannel channel = randomAccessFile.getChannel(); 
FileLock lock = channel.lock(); 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
try { 
    OutputStream fos = Channels.newOutputStream(channel); 
    try { 
     System.out.println("Lock obtained. Enter to exit"); 
     br.readLine(); 
     System.out.println("Done"); 
    } finally { 
     fos.close(); 
    } 
} catch (FileNotFoundException ex) { 
} 
+0

哇。這有幫助。 –

+0

我更新了代碼以使用通道,而不是創建新的FileOutputStream。那麼你只需關閉頻道[fos.close()],鎖就會被釋放。 –

0

使用FileOutputStream中和/或RandomAccessFile的這種方式不會給你鎖在文件..

相反,你應該使用的RandomAccessFile並獲得FileChannel然後出具文件鎖..

以下是您的示例修改:

public static void main(String[] args)throws IOException { 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     try { 
      RandomAccessFile raf = new RandomAccessFile(new File("d:/lockfile"), "rw"); 

      System.out.println("Requesting File Lock"); 
      FileChannel fileChannel = raf.getChannel(); 
      fileChannel.lock(); 
      try { 
       System.out.println("Lock obtained. Enter to exit"); 
       br.readLine(); 
       System.out.println("Done"); 
      } finally { 
       fileChannel.close(); 
      } 
     } catch (FileNotFoundException ex) { 
      System.out.println("No luck - file locked."); 
     } 
    } 
相關問題