Skip to content

Commit

Permalink
Merge pull request #989 from stevenschlansker/timer-runnable
Browse files Browse the repository at this point in the history
Add an overload of Timer#time that takes Runnable
  • Loading branch information
arteam committed Jan 5, 2017
2 parents 901424d + 55c1424 commit 15dde82
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
15 changes: 15 additions & 0 deletions metrics-core/src/main/java/com/codahale/metrics/Timer.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,21 @@ public <T> T time(Callable<T> event) throws Exception {
}
}

/**
* Times and records the duration of event.
*
* @param event a {@link Runnable} whose {@link Runnable#run()} method implements a process
* whose duration should be timed
*/
public void time(Runnable event) {
final long startTime = clock.getTick();
try {
event.run();
} finally {
update(clock.getTick() - startTime);
}
}

/**
* Returns a new {@link Context}.
*
Expand Down
20 changes: 20 additions & 0 deletions metrics-core/src/test/java/com/codahale/metrics/TimerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
Expand Down Expand Up @@ -69,6 +70,25 @@ public String call() throws Exception {
verify(reservoir).update(50000000);
}

@Test
public void timesRunnableInstances() throws Exception {
final AtomicBoolean called = new AtomicBoolean();
timer.time(new Runnable() {
@Override
public void run() {
called.set(true);
}
});

assertThat(timer.getCount())
.isEqualTo(1);

assertThat(called.get())
.isTrue();

verify(reservoir).update(50000000);
}

@Test
public void timesContexts() throws Exception {
timer.time().stop();
Expand Down

0 comments on commit 15dde82

Please sign in to comment.