Reputation: 63
Process A writes in a file XYZ, when executed. There are processes B and C, which when executed, reads the file XYZ. So, while process A is up, B and C should wait for A to complete. To provide synchronization can I use java.nio package? or I should use something like FileLock or sockets? Can we mention the time to wait for the second process to wait?
Edited: The file is created during the first write process. In such case, can I make it shared resource?
Upvotes: 4
Views: 1720
Reputation: 762
Using java.nio package's file lock could be a better solution, I hope. But, I think java.nio is not full-fledged till JDK 1.6. http://www.withoutbook.com/DifferenceBetweenSubjects.php?subId1=7&subId2=43&d=Java%206%20vs%20Java%207
FileLock: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html
Upvotes: 1
Reputation: 267
Using locks would be a good idea. You can use Conditions from JavaAPi. Refer to [http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#awaitNanos(long)][1]
When A is working it should signal the thread to await and then on completion it can signal so that other thread waiting to start can proceed. Also this is very appropriate when we use shared resource.
Upvotes: 0
Reputation: 840
One way could be the usage of a flag. Just a boolean stillWriting
which is readable from outside.
As soon process A did its Job, this flag is set to false
and your processes B/C can start their work with this file.
Assuming A wants to start again editing this file, it'll set this flag back to true
and block the other two processes.
Upvotes: 0