/** * Creates a store based on given configuration parameters. * * @param capacity the maximum number of connections the store can manage * @param threshold the period of time of inactivity (in seconds) after which a * connection is considered stale and can be evicted from the store if * a new connection is to be added to the store * @param sessionCache a second level cache to use for <em>current</em> * connection state of established DTLS sessions. */ public InMemoryConnectionStore(final int capacity, final long threshold, final SessionCache sessionCache) { connections = new LeastRecentlyUsedCache<>(capacity, threshold); this.sessionCache = sessionCache; if (sessionCache != null) { // make sure that session state for stale (evicted) connections is removed from second level cache connections.addEvictionListener(new LeastRecentlyUsedCache.EvictionListener<Connection>() { @Override public void onEviction(Connection staleConnection) { removeSessionFromCache(staleConnection); } }); } LOG.log(Level.CONFIG, "Created new InMemoryConnectionStore [capacity: {0}, connection expiration threshold: {1}s]", new Object[]{capacity, threshold}); }
@Test public void testContinuousEviction() { int capacity = 10; givenACacheWithEntries(capacity, 0L, 0); assertThat(cache.remainingCapacity(), is(capacity)); final AtomicInteger evicted = new AtomicInteger(0); cache.addEvictionListener(new EvictionListener<String>() { @Override public void onEviction(String evictedSession) { evicted.incrementAndGet(); } }); int noOfSessions = 1000; for (int i = 0; i < noOfSessions; i++) { Integer key = i +1000; String value = String.valueOf(key); assertTrue(cache.put(key, value)); } assertThat(evicted.get(), is(noOfSessions - capacity)); assertThat(cache.remainingCapacity(), is(0)); }