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

com.taobao.drc.clusterclient.NotifyController Maven / Gradle / Ivy

There is a newer version: 5.0.0.1.beta
Show newest version
package com.taobao.drc.clusterclient;

import com.taobao.drc.clusterclient.util.Gaugeable;
import com.taobao.drc.clusterclient.util.Time;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author yangyang
 * @since 17/6/23
 */
public class NotifyController implements Gaugeable {
    private static final String KEY_NOTIFIED_MESSAGE_SIZE = "notified.size";
    private static final String KEY_NOTIFIED_MESSAGE_SAMPLE_PERIOD_MS = "notified.sample_period_ms";
    private static final String KEY_NOTIFIED_MESSAGE_RPS = "notified.rps";

    private final Time time;

    private volatile long expirationMs = 0;
    private volatile boolean closed = false;
    private volatile long lastNotifiedMs = 0;
    private volatile long notifiedCounter = 0;
    private volatile long lastSampleCounter = 0;
    private volatile long lastSampleMs = 0;
    private volatile boolean notifying = false;

    public NotifyController(Time time) {
        this.time = time;
    }

    public boolean isNotifying() {
        return notifying;
    }

    public void setNotifying(boolean notifying) {
        this.notifying = notifying;
    }

    public void onNotified(R message) {
        lastNotifiedMs = time.millis();
        notifiedCounter++;
    }

    public long getLastNotifiedMs() {
        return lastNotifiedMs;
    }

    public boolean isValid() {
        return !isClosed() && time.millis() < expirationMs;
    }

    public void extendLeaseTo(long targetMs) {
        this.expirationMs = targetMs;
    }

    public boolean isClosed() {
        return closed;
    }

    public void close() {
        closed = true;
    }
    public void open(){closed = false; }

    @Override
    public Map getMetrics() {
        Map map = new TreeMap();
        long now = time.millis();
        long sampleCounter = notifiedCounter;

        if (lastSampleMs > 0) {
            long periodMs = now - lastSampleMs;
            long msgNum = sampleCounter - lastSampleCounter;
            if (periodMs > 0) {
                map.put(KEY_NOTIFIED_MESSAGE_SAMPLE_PERIOD_MS, periodMs);
                map.put(KEY_NOTIFIED_MESSAGE_RPS, msgNum * 1000 / periodMs);
            }
            lastSampleMs = now;
            lastSampleCounter = sampleCounter;
        }

        map.put(KEY_NOTIFIED_MESSAGE_SIZE, notifiedCounter);
        return map;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy