package com.jay.monitor.data.server.factory;

import com.jay.monitor.data.server.factory.thread.TaskRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 消费线程执行器
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/7 - 17:21
 */
public abstract class AbstractThreadProcess<T> implements TaskRunnable {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private Queue<T> queue = new ArrayBlockingQueue<>(queueSize());

    private volatile boolean isEnable = true;

    protected int queueSize() {
        return 5000;
    }

    public boolean send(T req) {
        boolean add = queue.add(req);
        if (!add) {
            logger.warn("队列满了: " + this.getClass());
        }
        return add;
    }

    public abstract void consumer(T req);

    @Override
    public void stop() {
        isEnable = false;
    }

    @Override
    public String getThreadName() {
        return getClass().getSimpleName();
    }

    @Override
    public void run() {
        while (isEnable) {
            T request = queue.poll();
            try {
                if (request != null) {
                    consumer(request);
                } else {
                    Thread.sleep(10);
                }
            } catch (Throwable e) {
                logger.error("消费失败:", e);
            }
        }
    }
}
