在创建我的应用程序时.体系结构我面临着一种结构的需求,下面将对此进行描述.
我很确定,有一个众所周知的具有相同功能的设计模式,因为我认为我为之开发的这个问题确实很普遍.
我为此编写了自己的实现,但是我始终尝试使用模式的“语言构建”实现,所以-请帮助我命名此结构.
这个想法接近于读者-作家模式.我们有一个“容器”,可以在其中通过键()添加对象.我们也可以通过键获取此对象,并将其从容器中删除.
因此,实现的类应具有两种方法:
void putObject(Key key, Object object);
Object getObject(Key key); // remove <Key,Object> from container.
接下来是最有趣的.
此容器应在多线程环境中工作,如下所示:
>如果没有与键关联的对象,则在调用get(Key
key)方法,调用者线程应为此对象等待
容器.
>当另一个线程将调用putObject(Key key,Object object)
它应该检查是否有一些线程正在等待的方法
这个对象,如果是,则发出信号并唤醒线程,
等待.
我认为这是通用结构,是否具有“正式”名称?
我的Java实现此模式:
private static interface BlackBox {
public void addObject(IdObject object);
public IdObject getObject(ObjectId id);
}
private static class BlackBoxImpl implements BlackBox {
private final Lock conditionLock = new ReentrantLock();
private final Map<ObjectId, IdObject> savedObjects;
private final Map<ObjectId, Condition> waitingConditions;
public BlackBoxImpl() {
this.savedObjects = new ConcurrentHashMap<ObjectId, IdObject>(20);
this.waitingConditions = new ConcurrentHashMap<ObjectId, Condition>(20);
}
@Override
public void addObject(IdObject object) {
savedObjects.put(object.getId(), object);
if (waitingConditions.containsKey(object.getId())) {
Condition waitCondition = waitingConditions.get(object.getId());
conditionLock.lock();
waitCondition.signal();
conditionLock.unlock();
}
}
@Override
public IdObject getObject(ObjectId id) {
if (savedObjects.containsKey(id)) {
return savedObjects.get(id);
} else {
conditionLock.lock();
Condition waitCondition = conditionLock.newCondition();
waitingConditions.put(id, waitCondition);
waitCondition.awaitUninterruptibly();
conditionLock.unlock();
return savedObjects.get(id);
}
}
}
private static interface IdObject {
public ObjectId getId();
}
private static class IdObjectImpl implements IdObject {
protected final ObjectId id;
public IdObjectImpl(ObjectId id) {
this.id = id;
}
@Override
public ObjectId getId() {
return id;
}
}
private static interface ObjectId {
}
private static class ObjectIdImpl implements ObjectId {
}
解决方法:
我可能会使用类似
ConcurrentMap<K,BlockingQue<V>>.
使用Map的并发方法添加对.从您的队列中获取价值.使用ArrayBlockingQue(1).
大概是这样的:
static class MultiQueue<K, V> {
// The base structure.
final ConcurrentMap<K, BlockingQueue<V>> queues = new ConcurrentHashMap<>();
/**
* Put an item in the structure.
*
* The entry in the map will be created if no entry is currently there.
*
* The value will then be posted to the queue.
*/
public void put(K k, V v) throws InterruptedException {
// Make it if not present.
ensurePresence(k).put(v);
}
/**
* Get an item from the structure.
*
* The entry in the map will be created if no entry is currently there.
*
* The value will then be taken from the queue.
*/
public void get(K k) throws InterruptedException {
// Make it if not present - and wait for it.
ensurePresence(k).take();
}
private BlockingQueue<V> ensurePresence(K k) {
// Make it if not present.
return queues.computeIfAbsent(k, v -> new ArrayBlockingQueue(1));
}
}