Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Temporary File Multithreaded Application

Tags:

java

I'm looking for a foolproof way to generate a temporary file that will have always end up with a unique name on a per JVM basis. Basically I want to be sure in a multithreaded application that if two or more threads attempt to create a temporary file at the exact same moment in time that they will both end up with a unique temporary file and no exceptions will be thrown.

This is the method I have currently:

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 perfectly safe for what my goal is? I reviewed the documentation at the below URL but I'm not sure.

See java.io.File#createTempFile

like image 741
Kabron Avatar asked Jul 07 '26 22:07

Kabron


2 Answers

The answer posted at the below URL answers my question. The method I posted is safe in a multithreaded single JVM process environment. To make it safe in a multithreaded multi-JVM process environment (e.g. a clustered web app) you can use Chris Cooper's idea which involves passing a unique value in the prefix argument for the File.createTempFile method within each JVM process.

Is createTempFile thread-safe?

like image 89
Kabron Avatar answered Jul 10 '26 11:07

Kabron


Just use the thread name and current time in millis to name the file.

like image 45
Sudhanshu Umalkar Avatar answered Jul 10 '26 12:07

Sudhanshu Umalkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!