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

shz.core.accept.QueueAcceptor Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
package shz.core.accept;

import shz.core.NullHelp;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class QueueAcceptor extends Acceptor {
    protected final Queue queue = new ConcurrentLinkedQueue<>();
    protected final AtomicInteger size = new AtomicInteger();
    private final Queue bufQueue = new LinkedList<>();

    protected QueueAcceptor(String threadName) {
        super(threadName);
        init();
    }

    protected QueueAcceptor() {
        super();
        init();
    }

    protected void init() {
        start();
    }

    @Override
    protected final Duration action() {
        int batchSize = batchSize();
        if (batchSize > 1) {
            while (!queue.isEmpty()) {
                bufQueue.add(queue.poll());
                size.decrementAndGet();

                if (bufQueue.size() >= batchSize) {
                    executeQuietly(new ArrayList<>(bufQueue));
                    bufQueue.clear();
                }
            }
            if (bufQueue.size() > 0) {
                if (bufQueue.size() == 1) execute(bufQueue.poll());
                else {
                    executeQuietly(new ArrayList<>(bufQueue));
                    bufQueue.clear();
                }
            }
        } else {
            while (!queue.isEmpty()) executeQuietly(queue.poll());
        }
        return null;
    }

    protected int batchSize() {
        return 1;
    }

    protected abstract void execute(T t);

    private void executeQuietly(T t) {
        try {
            execute(t);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    protected void execute(List list) {
        if (NullHelp.nonEmpty(list)) list.forEach(this::execute);
    }

    private void executeQuietly(List list) {
        try {
            execute(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    protected final boolean offer(T t) {
        if (t == null) return false;
        if (size.get() >= queueSize()) return overStrategy(t);
        size.incrementAndGet();
        queue.offer(t);
        return true;
    }

    protected int queueSize() {
        return 60000;
    }

    protected boolean overStrategy(T t) {
        //超过限制大小默认丢弃较早数据
        if (queue.poll() != null) size.decrementAndGet();
        size.incrementAndGet();
        queue.offer(t);
        return true;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy