Java temporary file multithreaded application
I'm looking for a simple way to generate a temporary file that always ends with a unique name on a per JVM basis Basically, I want to make sure that in a multithreaded application, if two or more threads try to create a temporary file at exactly the same time, they will eventually get a unique temporary file and will not throw any exceptions
This is my current approach:
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; }
Is this completely safe for my goal? I checked the documents at the following URL, but I'm not sure
See Java io. File#createTempFile
Solution
The answers posted on the following website answer my question The method I published is safe in a multithreaded single JVM process environment To make it safe in a multithreaded and multi JVM process environment, such as a Clustered Web application, you can use Chris Cooper's idea, which involves file Pass a unique value in the prefix parameter of the createtempfile method
Is createTempFile thread-safe?