Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

Create Temporary Files with NIO 2 on Linux

$
0
0
We have an application that had problems with memory consumption. One type of object that we were keeping in memory was kept there only in case a user would start an administration client and connect it to our app. So instead of having it constantly in memory, we decided to serialize it into a temporary file that would be destroyed when the application would stop. When an admin would connect, we would read back the data and send it before removing it from memory again.

The code that created the temporary file looked more or less like that:

  Path dir = Paths.get("myDir");
  Path tempFile = Files.createTempFile(dir, "MyApp", null);

  OutputStream outputStream = Files.newOutputStream(tempFile, StandardOpenOption.DELETE_ON_CLOSE);

As you see, the creation of a temporary file goes in two steps. First, the createTempFile() method would create a unique name with the given prefix. Then, the DELETE_ON_CLOSE option would delete the file when it was closed, that is in our case when the application would exit.

All our tests conducted in development on Windows platform would work fine. However, our test team ran all their tests on a Linux platform, which was actually the target platform for production. And guess what? It failed. The file would be created fine, and data was written without any problem. But when an admin would connect, the application would return a FileNotFoundException. When we checked, indeed, the files were not there.

After some investigation, it turned out that the DELETE_ON_CLOSE option on Linux platform would delete the file immediately from the file system, while keeping a reference to it in the Output Stream so that we could still write to it. How did we fix it? By turning to a good old non-NIO method:

  Path dir = Paths.get("myDir");
  Path tempFile = Files.createTempFile(dir, "MyApp", null);
  tempFile.toFile().deleteOnExit();
  OutputStream outputStream = Files.newOutputStream(tempFile);


Viewing all articles
Browse latest Browse all 73

Trending Articles