com.opentable.concurrent.TimerWrapper Maven / Gradle / Ivy
/**
* Copyright (C) 2012 Ness Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.opentable.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
class TimerWrapper extends CallableWrapper
{
private final Metrics metrics;
TimerWrapper(String threadPoolName, MetricRegistry registry)
{
this.metrics = new Metrics(threadPoolName, registry);
}
@Override
@SuppressWarnings("PMD.PrematureDeclaration")
public Callable wrap(final Callable callable)
{
final long enqueueNanos = System.nanoTime();
final Metrics myMetrics = metrics;
myMetrics.enqueueMeter.mark();
return new Callable() {
@Override
public T call() throws Exception
{
myMetrics.queueTimer.update(System.nanoTime() - enqueueNanos, TimeUnit.NANOSECONDS);
myMetrics.dequeueMeter.mark();
try {
return callable.call();
} catch (Throwable t) {
myMetrics.exceptionMeter.mark();
throw t;
} finally {
myMetrics.totalTimer.update(System.nanoTime() - enqueueNanos, TimeUnit.NANOSECONDS);
}
}
};
}
static class Metrics
{
private final String threadPoolName;
Meter exceptionMeter;
Meter enqueueMeter;
Meter dequeueMeter;
Timer queueTimer;
Timer totalTimer;
Metrics(String threadPoolName, MetricRegistry registry)
{
this.threadPoolName = threadPoolName;
exceptionMeter = registry.meter(metricName("exception"));
enqueueMeter = registry.meter(metricName("enqueue"));
dequeueMeter = registry.meter(metricName("dequeue"));
queueTimer = registry.timer(metricName("queued-duration"));
totalTimer = registry.timer(metricName("total-duration"));
}
private String metricName(final String name) {
return MetricsUtil.metricName(threadPoolName, name);
}
}
}