3 回答
TA贡献2051条经验 获得超10个赞
你需要的是这样的:
class Cache {
final ReentrantLock lock;
public Cache { lock = new ReentrantLock(); }
Entry addIfMissing(String data) {
lock.lock();
try {
// Add data here
}
finally {
lock.unlock();
}
}
void evictOldEntries() {
if (lock.tryLock()) {
try {
// Evict old entries
}
finally {
lock.unlock();
}
}
}
}
TA贡献2037条经验 获得超6个赞
由于您的代码示例和确切要求有点不清楚,因此在这里有点自由。但是这样的事情可能行得通吗?ConcurrentHashMap使用细粒度锁定,因此可以最大限度地减少将条目插入缓存时的瓶颈。逐出线程甚至可以与插入线程同时运行。
class Cache<String, CacheEntry> {
ConcurrentHashMap<String, CacheEntry> map = new ConcurrentHashMap<String, CacheEntry>();
Entry addIfMissing(String data) {
map.computeIfAbsent(...);
}
void evictOldEntries() {
Iterator<Map.Entry<String, CacheEntry>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
CacheEntry entry = iterator.next().getValue();
if (shouldEvict(entry)) {
iterator.remove();
}
}
}
}
TA贡献1843条经验 获得超7个赞
我认为ReentrantReadWriteLock正是我所需要的:
class Program {
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
void doWork() { // called from multiple threads
rwl.readLock().lock();
try {
var entry = cache.addIfMissing("omitted for brevity");
// work with entry
} finally {
rwl.readLock().unlock();
}
}
static {
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
rwl.writeLock().lock();
try {
cache.evictOldEntries();
} finally {
rwl.writeLock().unlock();
}
}, 10, 10, TimeUnit.MINUTES);
}
}
这样一旦获得 writeLock 就doWork必须阻塞,反之亦然。
添加回答
举报