Guarded Suspension 守衛模式
能處理多客戶端請求,若柱列區無資料時,處理元件就等待, 若有新加入,元件將會啟用。
@Slf4j
public abstract class AbtractCmd<T> implements ICommand<T> {
private volatile LinkedList<T> list = new LinkedList<T>();
private final int size;//柱列限制筆數
public AbtractCmd(int size) {
this.size = size;
}
public synchronized void add(T i) {
boolean canAdd = this.canAdd();
if (canAdd) {
this.list.add(i);
log.info("list:{}, add item:{}", this.list, i);
notifyAll();
} else {
try {
wait();
this.add(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private boolean canAdd() {
return list.size() < size;
}
@Override
public synchronized T execute() throws InterruptedException {
if (!this.ready()) {
// log.info("wait job");
wait();
} else {
T poll = this.list.poll();
notifyAll();
return poll;
}
return execute();
}
private boolean ready() {
return !list.isEmpty();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
}
Last updated
Was this helpful?