🎨
Andy開發紀錄
  • 關於
    • 自介
  • 設計模式
    • 觀察者模型
    • 有限狀態機
    • 裝飾器模式
  • 其他
    • Scrum敏捷式開發
    • SOLID設計
    • TDD驅動測試開發
    • Event Driven Architecture
    • CQRS命令查詢職責分離
    • Concurrent並行相關
      • Single Thread Execution
      • 共用元件設計
        • CountDownLatchWorkPool
        • IForkWorkService
      • Pattern
        • THREAD-PER-MESSAGE
        • PRODUCER CONSUMER
        • SINGLE THREAD
        • Guarded Suspension 守衛模式
      • IQueue
        • ListQueue
        • BlockQueue
        • OrderBlockQueue
  • 元件設計
    • Sql Help
      • SQL Help Generate
      • StringBuilderGenerator
      • SQL Generate
    • excel工具
    • BDD行為驅動開發
    • 多工設計
      • 多工自動調整Thread數量
    • 常用Design Patten實作
    • Telegram Bot元件
    • 代碼元件
    • HCP API元件
    • 文字解析元件
    • MockitObject
    • 資料驗證元件
    • Zip壓縮工具
    • Sql Code Generate
  • 讀書心得
    • Clean code第一章
  • side project
    • 後端服務
  • IDEA
    • IDEA 外掛推薦
    • IDEA 外掛開發
Powered by GitBook
On this page

Was this helpful?

  1. 其他
  2. Concurrent並行相關
  3. Pattern

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();
	}

}
PreviousSINGLE THREADNextIQueue

Last updated 2 years ago

Was this helpful?