Synchronizing searches and modifications

大憨熊 提交于 2019-11-29 12:41:57

Usually, yes ReadWriteLock is good enough.

But, if you're using Java 8 you can get a performance boost with the new StampedLock that lets you avoid the read lock. This applies when you have much more frequent reads(searches) compared with writes(edits).

private StampedLock sl = new StampedLock();

public void edit() { // write method
    long stamp = sl.writeLock();
    try {
      doEdit();
    } finally {
      sl.unlockWrite(stamp);
    }
}    

public Object search() { // read method
     long stamp = sl.tryOptimisticRead();
     Object result = doSearch(); //first try without lock, search ideally should be fast
     if (!sl.validate(stamp)) { //if something has modified
        stamp = sl.readLock(); //acquire read lock and search again
        try {
          result = doSearch();
        } finally {
           sl.unlockRead(stamp);
        }
     }
     return result;
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!