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?
- Any reason for this approach? Do you have to use a text file?user11044402– user110444022019-09-02 10:02:50 +00:00Commented Sep 2, 2019 at 10:02
- Yes, I have to use a text file.A6SE– A6SE2019-09-02 10:05:00 +00:00Commented Sep 2, 2019 at 10:05
- Would you tell use why? Why not a socket? Why not a message passing library?user11044402– user110444022019-09-02 10:05:44 +00:00Commented Sep 2, 2019 at 10:05
- It's not up to me. I was assigned this specific task as a part of the bigger project.A6SE– A6SE2019-09-02 10:11:13 +00:00Commented Sep 2, 2019 at 10:11
- You could use a file lock (stackoverflow.com/questions/128038/…) 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– Malt2019-09-02 10:16:38 +00:00Commented Sep 2, 2019 at 10:16
Add a comment |
1 Answer
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.tmptoabc.txt. You can use thejava.io.File.renameToorjava.nio.Files.movemethods for renaming.
The reader will then only be able to see completely written files in abc.txt.