Fritz
Fritz

Reputation: 882

Java 8 Lambda for Anonymous Class

I have a tricky situation here, which I would like to optimize from the code perspective. Is there any way to shorten the following method via Lambda / Java8 expressions?

// total amount of audiences
registry.register("metric.persons.total", new CachedGauge<Integer>(1,TimeUnit.MINUTES) {
    @Override
    protected Integer loadValue() {
        return personService.findAll().size();
    }
});

The CachedGauge class is looking like this:

public abstract class CachedGauge<T> implements Gauge<T> {
    protected CachedGauge(long timeout, TimeUnit timeoutUnit) {
        ...
    }

    protected abstract T loadValue();
        ...
    }
}

Would be really great to see if there is a way, the tricky part here is that there is a default constructor and the class is parameterized.

best, fri

Upvotes: 2

Views: 592

Answers (2)

Fritz
Fritz

Reputation: 882

Just for completion of this thread, my Utils class looks like this

public class MetricUtils {

    public static <T> CachedGauge<T> cachedGauge(long timeout, TimeUnit timeoutUnit, Supplier<T> supplier) {
        return new CachedGauge<T>(timeout, timeoutUnit) {
            @Override
            protected T loadValue() {
                return supplier.get();
            }
        };
    }
}

Upvotes: 1

ZhongYu
ZhongYu

Reputation: 19672

registry.register("metric.persons.total", 
    CachedGauge.of(1,TimeUnit.MINUTES, ()->personService.findAll().size() ) 
);

And I think you can figure out how to implement CachedGauge.of(long, TimeUnit, Supplier<T>)

Upvotes: 5

Related Questions