2

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

2
  • Does personService come from the anonymous class's containing scope, or is it a public/protected field inherited from CachedGauge? Commented May 29, 2015 at 23:28
  • ah sorry... the person service is a protected field in the outer class, similar to the "registry" object Commented May 29, 2015 at 23:31

2 Answers 2

5
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>)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this looks good. Problem is, that the CachedGauge is 3rd party class, which I tried not to override... But I then create my own Utils class...
@Fritz - exactly. It's a util method that can be put anywhere.
1

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();
            }
        };
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.