StatItem { public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token.set(rate); lastResetTime = now; } int value = token.get(); boolean flag = false; while (value > 0 && !flag) { flag = token.compareAndSet(value, value - 1); value = token.get(); } return flag; } StatItem(String name, int rate, long interval); boolean isAllowable(); @Override String toString();  }
@Test public void testIsAllowable() throws Exception { statItem = new StatItem("test", 5, 1000L); long lastResetTime = statItem.getLastResetTime(); assertEquals(true, statItem.isAllowable()); Thread.sleep(1100L); assertEquals(true, statItem.isAllowable()); assertTrue(lastResetTime != statItem.getLastResetTime()); assertEquals(4, statItem.getToken()); }