我编写了一个Provider / Consumer类,试图再次实现强大的并发性。
我的问题是关于价值的交换。 我会验证我的方法。我的感觉是,并且仅当Value类是不可变的,对,这是一种不错的方法?
如果Value类不是不可变的,它是否应该包含一些锁定机制?
class ModuleProvider implements Module {
Value value = Value.UNSET;
private final ReentrantLock computeLock = new ReentrantLock();
private final ReadWriteLock valueLock = new ReentrantReadWriteLock();
public void compute() {
if (computeLock.tryLock()) {
// Do some heavy computation
valueLock.writeLock().lock();
value = xyz;
valueLock.writeLock().unlock();
computeLock.unlock();
}
}
// Is this the correct way?
public Value getValue() {
valueLock.readLock().lock();
Value local = value;
valueLock.readLock().unlock();
return local;
}
}
class ModuleConsumer implements Module {
Value value = Value.UNSET;
private final ReentrantLock computeLock = new ReentrantLock();
private final ReadWriteLock valueLock = new ReentrantReadWriteLock();
Module provider;
public void compute() {
if (computeLock.tryLock()) {
Value v = provider.getValue();
valueLock.writeLock().lock();
value = Value.from(v);
valueLock.writeLock().unlock();
computeLock.unlock();
}
}
public Value getValue() {
return value;
}
public void exportTo(PriorityBlockingQueue<Message> queue) {
}
}