dimanche 25 février 2018

Externally lock Cache for updates

I have 2 caches which are updated individually form various parts of my code. Every some time (e.g. 12 hours) I want to make sure they are synced. An external class is responsible for starting and executing this task. How can I make sure other classes are not working with the caches when this happens?

My thinking is using some ReadWriteLock in each cache and exposing lock/unlock methods.

Class Cache {
  private final ReadWriteLock lock = new ReentrantReadWriteLock();

  public void put(String id, Object object) {
    lock.readLock().lock();
    try {
      // put in cache
    } finally {
      lock.readLock().unlock();
    }
  }

  public Object get(String id) {
  lock.readLock().lock();
    try {
      // get from cache
    } finally {
      lock.readLock().unlock();
    }
  }

  public void lock() {
    lock.writeLock().lock();
  }

  public void unlock() {
    lock.writeLock().unlock();
  }
}

And this is the code for the sync class

Class Synchronizer {
  Cache cache1 = new Cache();
  Cache cache2 = new Cache();

  public void syncCaches() {
    cache1.lock();
    cache2.lock();

    try {
      // do sync
    } finally {
      cache1.unlock();
      cache2.unlock();
    }
  }
}

This works, but I think it's a misuse of the Read/Write lock architecture and I couldn't find libraries or something else what might work.

Any ideas are welcome!

Aucun commentaire:

Enregistrer un commentaire