我正在寻找一个万无一失的方法来生成,将有总是在每个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