Sunny Gupta
Sunny Gupta

Reputation: 7067

Read Write File Through Multiple threads

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

Answers (4)

Tudor
Tudor

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

Marko Topolnik
Marko Topolnik

Reputation: 200138

Definitely use something from java.util.concurrent. I'd suggest two CountDownLatches here. Writing happens in one thread before calling cdl1.countDown and cdl2.await; the reading thread does the opposite.

Upvotes: 0

Martin James
Martin James

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

pcalcao
pcalcao

Reputation: 15965

I would use a Lock shared between the threads.

Since only one thread would hold the lock at any given time, you would make sure that the writing thread would only write to the file when the reading thread had released the lock (on a finally block!)

Upvotes: 2

Related Questions