}
}
@Test
public void testScopeSingleThread() throws Exception {
final MetricsScope fooScope = Metrics.startScope(scopeName);
// the time and number counters become available only after the 1st
// scope close:
expectIOE(new Callable<Long>() {
@Override
public Long call() throws Exception {
Long num = fooScope.getNumCounter();
return num;
}
});
expectIOE(new Callable<Long>() {
@Override
public Long call() throws Exception {
Long time = fooScope.getTimeCounter();
return time;
}
});
// cannot open scope that is already open:
expectIOE(new Callable<Void>() {
@Override
public Void call() throws Exception {
fooScope.open();
return null;
}
});
assertSame(fooScope, Metrics.getScope(scopeName));
Thread.sleep(periodMs+1);
// 1st close:
// closing of open scope should be ok:
Metrics.endScope(scopeName);
expectIOE(new Callable<Void>() {
@Override
public Void call() throws Exception {
Metrics.endScope(scopeName); // closing of closed scope not allowed
return null;
}
});
assertEquals(Long.valueOf(1), fooScope.getNumCounter());
final long t1 = fooScope.getTimeCounter().longValue();
assertTrue(t1 > periodMs);
assertSame(fooScope, Metrics.getScope(scopeName));
// opening allowed after closing:
Metrics.startScope(scopeName);
// opening of already open scope not allowed:
expectIOE(new Callable<Void>() {
@Override
public Void call() throws Exception {
Metrics.startScope(scopeName);
return null;
}
});
assertEquals(Long.valueOf(1), fooScope.getNumCounter());
assertEquals(t1, fooScope.getTimeCounter().longValue());
assertSame(fooScope, Metrics.getScope(scopeName));
Thread.sleep(periodMs + 1);
// Reopening (close + open) allowed in opened state:
fooScope.reopen();
assertEquals(Long.valueOf(2), fooScope.getNumCounter());
assertTrue(fooScope.getTimeCounter().longValue() > 2 * periodMs);
Thread.sleep(periodMs + 1);
// 3rd close:
fooScope.close();
assertEquals(Long.valueOf(3), fooScope.getNumCounter());
assertTrue(fooScope.getTimeCounter().longValue() > 3 * periodMs);
Double avgT = (Double)Metrics.get("foo.avg_t");
assertTrue(avgT.doubleValue() > periodMs);
}