javatomcattemp

Is it safe to delete all .tmp files in tomcat/temp while server is running? Tomcat 8.5.64


Our server has a problem with the tomcat/temp dir filling up and not clearing itself.

I wrote a scheduled task that runs every two days and deletes all .tmp files older than two days.

This should be safe, no? I read that it is only truly safe to purge /temp when the server is shutdown, but I don't see why old temp files should be needed. The temp files filling up the directory are from user file uploads.

The tomcat.pid file also resides in /temp, but it would be excluded from the purge, since only .tmp files are deleted.

Java 8 solution:

public static void removeAllTemporaryFiles(TempFilePaths chosenFilePath) {
  Date ageLimit = DateHelper.addToDate(DateHelper.today(), -2, TimeUnit.DAYS);
  String filePath = null;
  IOFileFilter fileFilter = null;
  switch (chosenFilePath){
    // other cases
    case TOMCATTEMP:
      filePath = PathMapper.getInstance().getPath("tomcatTemp", "unknown").toString();
      fileFilter = new AndFileFilter(new AgeFileFilter(ageLimit, true), new WildcardFileFilter("*.tmp"));
      break;
    // other cases
  }

  if (FileHelper.exists(filePath)) {
    Collection<File> filesToDelete = FileUtils.listFiles(new File(filePath), fileFilter, TrueFileFilter.INSTANCE);
    int numberOfFilesToBeDeleted = filesToDelete.size();
    int filesDeletedCounter = 0;
    for (File fileObject : filesToDelete) {
      try {
        fileObject.delete();
        filesDeletedCounter++;
      } catch (Exception e) {
        log.error(e);
      }
    }
    log.info("Temporary files deleted @ " + filePath + ": " + filesDeletedCounter + "/" + numberOfFilesToBeDeleted);
  }
}

Solution

  • Nobody can tell you for sure:

    Any app that's running in the server might expect their temporary files to live for a certain time.

    E.g. you might delete a file that is currently in the process of being uploaded to the server, and stored in the temp directory until it's received and processed. (you avoid this by deleting files of a certain age, but as this question might be found by others, who intend to delete everything, I'll leave this warning here)

    Just blindly deleting those files might work most of the time, but only fail rarely in some hard to reproduce corner cases (e.g. when upload of a large file happens at the same time as your purging job)

    You made a good choice to delete files only when they've reached a certain age - but even then it depends on the apps that have created the temp files.

    From Tomcat's (server) point of view, I'm not aware of bad side effects.

    If you find an app that depends on 2 days old temp files, I'd say you can go back to its developers and demand a fix. But that might not save you from trouble. If you have control over the apps, you might want to change them to delete what they don't need any more.