我想保護我的代碼不會同時在一個目錄中做同樣的事情,而且我需要一種跨進程互斥體。由於有問題的目錄最終可能會在整個網絡上共享,我通過打開一個文件來寫作這種鎖。爲什麼我可以打開同一個文件在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。
我的錯誤在哪裏?這怎麼可能?
而不是打開該文件,您可以創建該文件以獲取鎖定並刪除該文件釋放它。 – DaoWen