NonceManager { public synchronized boolean verify(String key, String timestamp, String nonce) { long now = System.currentTimeMillis(); long stamp = longValue(timestamp) * 1000; if (stamp + maxAge < now) { return false; } Map<String, Set<String>> keyToNonces = tsToKeyNoncePairs.get(stamp); if (keyToNonces == null) { keyToNonces = new HashMap<String, Set<String>>(); tsToKeyNoncePairs.put(stamp, keyToNonces); } Set<String> nonces = keyToNonces.get(key); if (nonces == null) { nonces = new HashSet<String>(); keyToNonces.put(key, nonces); } boolean result = nonces.add(nonce); if (++gcCounter >= gcPeriod) { gc(now); } return result; } NonceManager(long maxAge, int gcPeriod); synchronized boolean verify(String key, String timestamp, String nonce);  }
@Test public void testDuplicateNonce() { NonceManager nonces = new NonceManager(1000, 50); String stamp = stamp(); boolean accepted; accepted = nonces.verify("nonce-key", stamp, "nonce"); assertTrue(accepted); accepted = nonces.verify("nonce-key", stamp, "nonce"); assertFalse(accepted); }