我正在尋找一個萬無一失的方法來生成,將有總是在每個JVM基礎的唯一名稱結束了一個臨時文件。基本上,我想確保在多線程應用程序中,如果兩個或更多線程試圖在同一時刻創建臨時文件,它們都將以唯一臨時文件結束,並且不會拋出異常。Java的臨時文件多線程應用程序
這是我的方法目前有:
public File createTempFile(InputStream inputStream) throws FileUtilsException {
File tempFile = null;
OutputStream outputStream = null;
try {
tempFile = File.createTempFile("app", ".tmp");
tempFile.deleteOnExit();
outputStream = new FileOutputStream(tempFile);
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
logger.debug("Unable to create temp file", e);
throw new FileUtilsException(e);
} finally {
try { if (outputStream != null) outputStream.close(); } catch (Exception e) {}
try { if (inputStream != null) inputStream.close(); } catch (Exception e) {}
}
return tempFile;
}
是我的目標是什麼,這一完全安全嗎?我在下面的URL中查看了文檔,但我不確定。
我認爲這個問題是在這裏找到答案:http://stackoverflow.com/questions/4702537/is-createtempfile-thread-safe – 2013-03-21 17:15:55
根據javadoc的這種方法可能會拋出異常,因此你的代碼應該是能夠處理這些例外。比重名等原因,可能會出現錯誤,例如磁盤故障等 編輯:另外這個方法是靜態的,所以線程(如果你信任你的JDK實現) – 2013-03-21 17:16:56
@AndreasBakurov - 僅僅因爲一個方法被標記'static'不**使它線程安全。實際上,標記「static」通常是線程/併發錯誤的原因。 – 2013-03-21 17:28:41