Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...