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

net.yudichev.jiotty.common.lang.throttling.ThresholdThrottlingConsumer Maven / Gradle / Ivy

There is a newer version: 2.3.0
Show newest version
package net.yudichev.jiotty.common.lang.throttling;

import com.google.inject.assistedinject.Assisted;
import net.yudichev.jiotty.common.time.CurrentDateTimeProvider;

import javax.annotation.concurrent.NotThreadSafe;
import javax.inject.Inject;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Consumer;

import static com.google.common.base.Preconditions.checkNotNull;

@NotThreadSafe
public final class ThresholdThrottlingConsumer implements Consumer {
    private final CurrentDateTimeProvider currentDateTimeProvider;
    private final ThresholdGatedConsumer thresholdGatedConsumer;
    private final Duration throttlingDuration;
    private Instant nextTimeout;

    @Inject
    ThresholdThrottlingConsumer(CurrentDateTimeProvider currentDateTimeProvider,
                                @Assisted int threshold,
                                @Assisted Duration throttlingDuration,
                                @Assisted Consumer delegate) {
        this.currentDateTimeProvider = checkNotNull(currentDateTimeProvider);
        thresholdGatedConsumer = ThresholdGatedConsumer.thresholdGated(threshold, delegate);
        this.throttlingDuration = checkNotNull(throttlingDuration);
    }

    @Override
    public void accept(T t) {
        Instant now = currentDateTimeProvider.currentInstant();
        if (nextTimeout != null && now.isAfter(nextTimeout)) {
            thresholdGatedConsumer.reset();
        }
        nextTimeout = now.plus(throttlingDuration);
        thresholdGatedConsumer.accept(t);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy