Reputation: 7067
I want to read and write in a same file through threads.
But the condition is when the first thread finishes reading only then the other thread should write.
The solution that I proposed was:
class XYX {
public void read(){
synchronised(fileObj){
//write the reading logic
}
}
public void write(){
synchronised(fileObj){
//write the writing logic
}
}
}
Please let me know your ideas
I want to retain this Ordering
Reading - Writing - Reading - Writing - Reading - so on
Upvotes: 1
Views: 2795
Reputation: 62439
If a total ordering of read-then-write must be maintained then it's easiest to use a monitor:
class XYX {
private final Object fileObj = new Object();
private volatile boolean writerWaits = true;
public void read(){
// read from file
synchronized(fileObj){
writerWaits = false;
fileObj.notify(); // signal the writer to begin
}
}
public void write(){
synchronized(fileObj){
while(writerWaits)
fileObject.wait(); // wait for signal from reader
}
// write to file
}
}
Upvotes: 0
Reputation: 200138
Definitely use something from java.util.concurrent
. I'd suggest two CountDownLatch
es here. Writing happens in one thread before calling cdl1.countDown
and cdl2.await
; the reading thread does the opposite.
Upvotes: 0
Reputation: 24847
I would use two semaphores one for read, one for write, with only one unit between them. The read method waits on the read semaphore, then reads, then signals the write semaphore. The writer waits on the write semaphore, then writes, then signals the read semaphore.
Upvotes: 0