Synchronizing searches and modifications

2019-01-27 11:28发布

What's a good way of allowing searches from multiple threads on a list (or other data structure), but preventing searches on the list and edits to the list on different threads from interleaving? I tried using synchronized blocks in the searching and editing methods, but that can cause unnecessary blocking when trying to run searches in multiple threads.

EDIT: The ReadWriteLock is exactly what I was looking for! Thanks.

1条回答
霸刀☆藐视天下
2楼-- · 2019-01-27 11:53

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;
   }
查看更多
登录 后发表回答