自带自动清理机制的阻塞队列

public class AutoClearBlockingQueue extends ArrayBlockingQueue {
    private final int clearThreshold;  // 触发清理的阈值
    private transient Consumer> clearCallback;  // 清理回调函数

    public AutoClearBlockingQueue(int capacity, double thresholdRatio) {
        super(capacity);
        this.clearThreshold = (int) (capacity * thresholdRatio);
    }

    // 设置清理回调函数
    public void setClearCallback(Consumer> callback) {
        this.clearCallback = callback;
    }

    @Override
    public void put(T item) throws InterruptedException {
        checkAndClear();  // 检查是否需要清理
        super.put(item);
    }

    @Override
    public boolean offer(T item) {
        checkAndClear();  // 检查是否需要清理
        return super.offer(item);
    }

    // 检查队列大小并执行清理
    private void checkAndClear() {
        if (size() >= clearThreshold) {
            clear();  // 调用父类清理方法
            if (clearCallback != null) {
                clearCallback.accept(this);  // 执行回调通知
            }
        }
    }
}

AutoClearBlockingQueue 是一个 自带自动清理机制 的阻塞队列,它在标准 ArrayBlockingQueue 的基础上增加了 阈值触发清空队列 的功能,并支持 回调通知

//示例用法

AutoClearBlockingQueue queue = new AutoClearBlockingQueue<>(100, 0.8);
queue.setClearCallback(q -> Log.d(TAG, "队列已自动清空"));

// 当添加第80个元素时,队列会被自动清空
for (int i = 0; i < 100; i++) {
    queue.offer("item " + i);
}

你可能感兴趣的:(自带自动清理机制的阻塞队列)