Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is createTempFile thread-safe?

I'm using Java 6.

Is it possible that two threads calling createTempFile (of the class java.io.File) get the same temp file?

like image 464
Russell Avatar asked Jan 15 '11 22:01

Russell


People also ask

What is Java 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.

How do I create a temp 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.

How do you create a temp file in Java without the random number appended to the filename?

Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.

How do I create a temp file in Kotlin?

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.


1 Answers

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..

like image 97
CodegistCRest Avatar answered Sep 27 '22 19:09

CodegistCRest