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

cn.geektool.core.observer.AbstractObServer Maven / Gradle / Ivy

package cn.geektool.core.observer;

import cn.geektool.core.timer.SystemClock;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 通用观察者服务.
 *
 * @author jiangdi
 * @since 0.0.1
 */
public abstract class AbstractObServer implements BaseObServer {

    /**
     * 观察者名称
     */
    private String name;

    /**
     * 调用的数据
     */
    public T data;

    /**
     * 调用方式
     */
    private ObserverType type = ObserverType.SYNC;

    /**
     * 运行次数
     */
    private AtomicInteger runCount = new AtomicInteger(0);

    /**
     * 最后次调用时间
     */
    private Long lastReqTime;

    @Override
    public String getName() {
        return this.name;
    }

    public Integer getExecuteCount() {
        return runCount.get();
    }

    public AbstractObServer name(String name) {
        this.name = name;
        return this;
    }

    @Override
    public ObserverType getType() {
        return this.type;
    }

    public AbstractObServer type(ObserverType type) {
        this.type = type;
        return this;
    }

    public Long getLastReqTime() {
        return this.lastReqTime;
    }

    @Override
    public void execute(T data) throws ExecutionException, InterruptedException {
        this.data = data;
        this.runCount.incrementAndGet();
        this.lastReqTime = SystemClock.now();
        //TODO 异步需重新考虑、CompletableFuture.runAsync(this::execute)在使用自旋锁时波动太大
        if (this.type == ObserverType.NSYNC) {
            CompletableFuture.runAsync(this::execute);
        } else {
            //默认为同步
            execute();
        }
    }

    /**
     * 封装提供实现
     */
    protected abstract void execute();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy