2017-06-17 140 views
-1

我有以下代碼:java.io.File構造函數行爲或可能是多線程問題?

class Abcd{ 
//wired by spring to give the directory filePath ="/var/tmp/" 
private String filePath; 

public void myMethod(String id, String date){ 
    filePath= filePath+ id+ "_" + date; 
    File f = new File(filePath); 
    if(f.exists){//Do something} 
    else{ 
    System.out.println("File not found at file path:"+filePath); 
    } 
} 
} 

上面的代碼行爲怪異,間歇性的文件路徑包含目錄/ var/tmp中/中的所有文件。所以,如果/ var/tmp目錄包含兩個名爲「id1_01012017」和「id2_10102017」的文件。

這是文件路徑沒有找到間歇輸出

文件:/ var/tmp中/ id1_01012017id2_10102017

我無法弄清楚發生了什麼

+0

該代碼確實不是線程安全的。如果從多個線程調用myMethod,可能會發生觀察到的行爲。 – Henry

回答

1

做,這是最好的方法保持filePath仍然不可變。你會發現,如果你改變這一行:

filePath = filePath + id + "_" + date; 

以下幾點:

String tempFilePath = filePath + id + "_" + date; 

tempFilePath而不是filePath操作,你的代碼會變得如預期線程安全和工作。

+0

即使這是一個線程問題,輸出應該是這樣的: 文件路徑找不到文件:/ var/tmp/id1_01012017/var/tmp/id1_01012017id2_10102017 對不對? – user2713255

+0

不一定。如果兩個線程通過相同的代碼運行,則沒有確定性的方式來預測輸出。 – erip