同步搜索和修改 [英] Synchronizing searches and modifications

查看:124
本文介绍了同步搜索和修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是允许从列表(或其他数据结构)上的多个线程进行搜索但阻止对列表的搜索以及对不同线程上的列表进行编辑的交错的一种好方法?我尝试在搜索和编辑方法中使用同步块,但是当尝试在多个线程中运行搜索时,这可能导致不必要的阻塞.

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.

ReadWriteLock正是我想要的!谢谢.

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

推荐答案

通常,是的ReadWriteLock就足够了.

但是,如果您使用的是Java 8,则可以通过新的

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

这篇关于同步搜索和修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆