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

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

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

import org.slf4j.Logger;

import javax.annotation.concurrent.NotThreadSafe;

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

@NotThreadSafe
public final class ThresholdExceptionLoggingRunnable implements Runnable {
    private final Runnable delegate;
    private final ThresholdGatedConsumer exceptionLoggingAction;

    private ThresholdExceptionLoggingRunnable(Runnable delegate, ThresholdGatedConsumer exceptionLoggingAction) {
        this.delegate = checkNotNull(delegate);
        this.exceptionLoggingAction = checkNotNull(exceptionLoggingAction);
    }

    public static Runnable withExceptionLoggedAfterThreshold(Logger logger, String description, int threshold, Runnable delegate) {
        return new ThresholdExceptionLoggingRunnable(delegate, ThresholdGatedConsumer.thresholdGated(threshold, e -> logger.error("Error when {}", description, e)));
    }

    @Override
    public void run() {
        try {
            delegate.run();
            exceptionLoggingAction.reset();
        } catch (RuntimeException e) {
            exceptionLoggingAction.accept(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy