alex314159 alex314159 - 3 months ago 15
Java Question

Java synchronization - waiting for data from server

I have a classic server / client problem where a class is waiting for a data update from a server at regular intervals. In a nutshell my program is as follows:

public synchronized void eodProcess() {
//DO STUFF
dataReady = false;
while (!dataReady) {
try {
wait();
} catch (InterruptedException e) {
}
}
//DO STUFF
}

public void update(){
//CODE THAT DOWNLOADS FROM SERVER
synchronized(this){
dataReady = true;
notifyAll();
}
}


Both eodProcess() and update() are scheduled to run at the same time every evening.

Now the code above has always worked as the data download takes a few seconds, but it seems like the wrong way of doing things, as in theory update() could run faster than eodProcess(), set dataReady to true, then eodProcess would set it to False and then wait forever. What would be the correct way of making sure eodProcess waits for the data to be ready?

I was thinking about scheduling a new process that would set dataReady to false a few minutes before either of the two methods and removing the initialization at the beginning of eodProcess, but that doesn't seem very clean.

Thanks,

Answer

This is a classic situation when application of CountDownLatch is useful.

CountDownLatch downloadDone = new CountDownLatch(1);

[...]

public synchronized void eodProcess() {
    //DO STUFF

    downloadDone.await();
  //DO STUFF
  }

public void update(){
    //CODE THAT DOWNLOADS FROM SERVER
    downloadDone.countDown();
}

It's basically a semaphore, but nicer. Await will only proceed when the latch counts down to zero (or the thread is interrupted). If you need the ability to reset the count, consider using CyclicBarrier (it works about the same, but there's a reset method)

Comments