St.Antario St.Antario - 1 month ago 4
Linux Question

Isn't it possible for a file to not be visible for other processes?

I have a Java application which is invoked from a shell script and creates a file, then writes some content to it. It works something like this:

File f = new File("/tmp/NEW_t.zip");
try(FileOutputStream fos = new FileOutputStream(f);
Writer writer = new OutputStreamWriter(fos)){
writer.write("Test string");
writer.write("another test string");
//lots of other writings


The resulting file will be quite large (up to 100MB). The issue is that opening the
FileOutputStream
creates an empty file and makes it available to other processes in the system.

In my case it causes a nasty bug because another process can read this file in an inconsistent state (empty).

Is it possible to make this file invisible for other processes until the process which created it has finished with it? Can it be resolved at the OS level or is there another solution?

Answer

Another way to do it is to store the file as .tmp or another naming convention until your first process is done with it completely, then rename it to the expected ingestion name. There are other, better ways of doing it in a program, but that's a question better answered in StackOverflow.

Comments