Deque仅当大小将超过限制时,才需要用新值替换第一个值。我写了这段代码来解决它:
final class Some {
final int buffer;
final Deque<Operation> operations = new ConcurrentLinkedDeque<>();
// constructors ommited;
@Override
public void register(final Operation operation) {
if (this.operations.size() == this.buffer) {
// remove the oldest operation
this.operations.removeFirst();
}
// add new operation to the tail
this.operations.addLast(operation);
}
@Override
public void apply() {
// take the fresh operation from tail and perform it
this.operations.removeLast().perform();
}
}
如您所见,我有两种方法可以修改Deque。我对此代码是否可以在多线程环境中正常运行感到怀疑。问题是:检查size()并随后执行修改ConcurrentLinkedDeque后的操作是否安全?我想要尽可能少的锁。因此,如果此代码行不通,那么我不得不引入锁定功能,那么使用毫无意义ConcurrentLinkedDeque()。
final class Some {
final int buffer;
final Deque<Operation> operations = new LinkedList<>();
final Lock lock = new ReentrantLock();
// constructors ommited;
@Override
public void register(final Operation operation) {
this.lock.lock();
try {
if (this.operations.size() == this.buffer) {
// remove the oldest operation
this.operations.removeFirst();
}
// add new operation to the tail
this.operations.addLast(operation);
} finally {
lock.unlock();
}
}
@Override
public void apply() {
this.lock.lock();
try {
// take the fresh operation from tail and perform it
this.operations.removeLast().perform();
} finally {
this.lock.unlock();
}
}
}
这是的替代选择Lock。那是实现我想要的唯一途径吗?我对尝试使用并发集合特别感兴趣。
守着星空守着你
相关分类