同步搜索和修改 [英] 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.
ReadWriteLock正是我想要的!谢谢.
The ReadWriteLock is exactly what I was looking for! Thanks.
推荐答案
通常,是的ReadWriteLock
就足够了.
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屋!