How do I synchronize data requests with the data refresh process?

I have an application that uses a cron job to update a dataset. The update process occurs once a minute and does not last long. The servlet provides this dataset to users. My problem is that during the update process, the servlet requests must block and wait for the process to complete.

On the bottom line, I have two functions:

private void updateData() {    
}

public List getData() {
}

      

The first function runs once a minute. The second can be called any number of times at the same time. When updateData is executed, all getData calls must wait for completion. A single call to getData should not block subsequent calls to the same function. The updateData function has a higher priority than getData, that is, when updateData needs to be run, it needs to wait for all getData calls to complete, but no new calls can be started.

What synchronization mechanism should I use for such a case? I am using a Java server, but I would be interested to know what solutions exist for other platforms as well.

0


source to share


4 answers


Take a look at this article: Reading / Writing Locks in Java



The only drawback I can see with this example is notifyAll () waking up all waiting threads. However, it takes precedence for write-lock requests.

+3


source


You can use ReadWriteLock instead of synchronization .

ReadWriteLock maintains a couple of related locks, one for read-only and one for writing. A read lock can be held concurrently by multiple reader threads if there are no writers. The write lock is exclusive.



public void updateData() {
    lock.writeLock().lock();
    try {
        /* do stuff. */
    } finally {
       lock.writeLock().unlock();
    }
}


public List getData() {
    lock.readLock().lock();
    try {
       /* process/return data. */
    } finally {
       lock.readLock().unlock();
    }

      

}

+5


source


You need to synchronize data access.

public void updateData() {
    synchronized (updateLock) {
        /* do stuff. */
    }
}


public List getData() {
    List data;
    synchronized (updateLock) {
        data = getRealData();
    }
    /* process/return data. */
}

      

0


source


CopyOnWriteArrayList or CopyOnWriteArraySet is something to look out for. I've used a lot of them in situations where updates aren't frequent.

0


source







All Articles