0

Assuming I have a simple Java program that writes something to some file using FileOutputStream (with default constructor FileOutputStream(File)) and two instances of this program are run concurrently (and they both write the same content to the same file), is there a chance that resulting file will be corrupted?

Here is the simple example that I tried:

    public static void main(String[] args) throws IOException {
        String content = args[0] + "\n";
        long startTime = System.currentTimeMillis();
        FileOutputStream fos = new FileOutputStream(new File("/Users/user/tmp/file.txt"));
        while (System.currentTimeMillis() - startTime < TimeUnit.SECONDS.toMillis(30)) {
            fos.write(content.getBytes());
        }
        fos.close();
    }

On my machine if I run one instance of this program with 1 argument and the second one with 2 argument I can see only 2 in the resulting file. Can I be sure that this will always be that way in any environment? Where does the information being written by the first instance go?

coolguy
  • 3,011
  • 2
  • 18
  • 35

1 Answers1

1

You haven't specified append=true in the constructor of FileOutputStream, so the last process to run (number 2) will overwrite the content written by the previous one.

With regards to multiple processes writing to the file, you want to use some sort of locking to prevent mixing of content. You can use a FileLock.

Check out this answer for help.

Community
  • 1
  • 1
Edd
  • 1,350
  • 11
  • 14
  • For some reasons I can't use file locking. But that's ok, if I can be sure that two processes writing the same data to the same file won't mess up this file this is totally fine for me – coolguy Mar 22 '17 at 09:40
  • For what reasons? If you can't use file locking, you can't write this application. Reconsider: rethink. – user207421 Mar 22 '17 at 10:59