I'm writing two programs that communicate through a text file. The first program writes to the file and the second one reads from it. However, there is a problem when the reader program tries to read from the file while the writer is still writing and reads inconsistent data. Is there a way to synchronize the read/write from two different JVMs?
Asked
Active
Viewed 347 times
0
-
Any reason for this approach? Do you *have* to use a text file? – Sep 02 '19 at 10:02
-
Yes, I have to use a text file. – A6SE Sep 02 '19 at 10:05
-
Would you tell use why? Why not a socket? Why not a message passing library? – Sep 02 '19 at 10:05
-
It's not up to me. I was assigned this specific task as a part of the bigger project. – A6SE Sep 02 '19 at 10:11
-
You could use a file lock (https://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible) The JVM holding the lock is the one that has access to the file. The other JVM will periodically poll the file, try to acquire the lock. – Malt Sep 02 '19 at 10:16
1 Answers
0
A simple solution that is often used:
- Write the text to a file with a different name than the reader expects. For example, if the expected filename is
abc.txt
, write to a file calledabc.txt.temp
. - Once writing is complete, rename the file to its intended name. On most (this is platform-dependent, though) filesystems, a rename of a file within the same directory is atomic - it will occur instantly. So in this case, rename is from
abc.txt.tmp
toabc.txt
. You can use thejava.io.File.renameTo
orjava.nio.Files.move
methods for renaming.
The reader will then only be able to see completely written files in abc.txt
.

Erwin Bolwidt
- 30,799
- 15
- 56
- 79