All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rx.bean.CircularBlockingQueue Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.bean;

import lombok.Getter;
import org.rx.core.*;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

public class CircularBlockingQueue extends LinkedBlockingQueue implements EventPublisher> {
    private static final long serialVersionUID = 4685018531330571106L;
    public final Delegate, T> onConsume = Delegate.create();
    public final Delegate, NEventArgs> onFull = Delegate.create();
    final ReentrantLock pLock = Reflects.readField(this, "putLock");
    TimeoutFuture consumeTimer;
    @Getter
    long consumePeriod;

    public void setCapacity(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        Reflects.writeField(this, "capacity", capacity);
    }

    public int getCapacity() {
        return Reflects.readField(this, "capacity");
    }

    public synchronized void setConsumePeriod(long consumePeriod) {
        if ((this.consumePeriod = consumePeriod) > 0) {
            if (consumeTimer != null) {
                consumeTimer.cancel();
            }
            consumeTimer = Tasks.timer().setTimeout(() -> {
                T t;
                while ((t = poll()) != null) {
                    raiseEvent(onConsume, t);
                }
            }, d -> consumePeriod, null, Constants.TIMER_PERIOD_FLAG);
        } else {
            if (consumeTimer != null) {
                consumeTimer.cancel();
            }
        }
    }

    public CircularBlockingQueue(int capacity) {
        super(capacity);
        onFull.combine((q, t) -> {
            pLock.lock();
            try {
                boolean ok;
                do {
                    q.poll();
                    ok = q.innerOffer(t.getValue());
                }
                while (!ok);
            } finally {
                pLock.unlock();
            }
        });
    }

    //Full会抛异常
//        @Override
//        public boolean add(T t) {
//            return offer(t);
//        }

    @Override
    public boolean offer(T t) {
        boolean r = super.offer(t);
        if (!r && onFull != null) {
            NEventArgs e = new NEventArgs<>(t);
            raiseEvent(onFull, e);
            return !e.isCancel();
        }
        return r;
    }

    protected boolean innerOffer(T t) {
        return super.offer(t);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy