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?