I'm using Java 6.
Is it possible that two threads calling createTempFile (of the class java.io.File) get the same temp file?
Creating a temporary fileThe File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.
To create and use a temporary fileThe application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.
Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.
File. createTempFile. Creates a new empty file in the specified directory, using the given prefix and suffix to generate its name. If prefix is not specified then some unspecified string will be used.
Best way to get your answer is to look at the source code. At first there isn't any synchronization in createTempFile, but to generate the temp file name, it is using SecureRandom which is ThreadSafe. Then unless you are really unlucky, your file will always get a different name.
On top of that, createTempFile implementation is looping, generating new file name, until the file has been created. The file creation of course is delegated to the native file system operation which we may assume is threadsafe..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With