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

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

java - Synchronizing searches and modifications

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...