Video in progress

How do you create temporary files, and what do you do so they don't pile up on disk?

Files.createTempFile(prefix, suffix) creates a file with a unique name. Then you must delete it in a try-finally with Files.deleteIfExists. Don't rely on deleteOnExit(): it only works when the JVM shuts down normally and can leak memory on a long-running server.

📖 Answer

Path tmp = Files.createTempFile("export-", ".csv");
try {
    writeCsv(tmp);
    s3.upload(tmp);
} finally {
    Files.deleteIfExists(tmp);
}

Why deleteOnExit is bad: it keeps the file path in an internal list until the JVM stops. A server runs for months and creates a new temp file on every request, so the list grows and the disk fills up.

What you need to know on prod:

  • the default directory is java.io.tmpdir, usually /tmp on Linux. On some systems it lives in RAM (tmpfs) and is small;
  • in Kubernetes, if the container file system is readOnlyRootFilesystem, you need an emptyDir volume for /tmp;
  • on POSIX systems createTempFile creates the file with permissions that let only the owner read it, which is good for security. The old File.createTempFile may give broader permissions;
  • if the application crashes, finally doesn't run. So sometimes a cleanup of old temp files is added at startup or as a scheduled job.

Tomcat also uses a temp directory for multipart uploads: one of the first places to look in a "disk is full" incident.