Skip to content

Commit

Permalink
finalized "threaded" version of LRUCache
Browse files Browse the repository at this point in the history
  • Loading branch information
jdereg committed Jun 23, 2024
1 parent 46dc3aa commit 2d5e69f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 14 deletions.
57 changes: 43 additions & 14 deletions src/main/java/com/cedarsoftware/util/LRUCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -43,12 +45,15 @@
* limitations under the License.
*/
public class LRUCache<K, V> extends AbstractMap<K, V> implements Map<K, V> {
private static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
private static final ScheduledExecutorService defaultScheduler = Executors.newScheduledThreadPool(1);
private static final Object NULL_ITEM = new Object(); // Sentinel value for null keys and values
private final long cleanupDelayMillis;
private final int capacity;
private final ConcurrentMap<Object, Node<K>> cache;
private final AtomicBoolean cleanupScheduled = new AtomicBoolean(false);
private final ScheduledExecutorService scheduler;
private final ExecutorService cleanupExecutor;
private boolean isDefaultScheduler;

private static class Node<K> {
final K key;
Expand All @@ -67,28 +72,45 @@ void updateTimestamp() {
}

/**
* Create a LRUCache with the maximum capacity of 'capacity.' Note, the LRUCache could temporarily exceed the
* capacity, however, it will quickly reduce to that amount. This time is configurable and defaults to 10ms.
*
* Create a LRUCache with the maximum capacity of 'capacity.' Note, the LRUCache could temporarily exceed the
* capacity, however, it will quickly reduce to that amount. This time is configurable and defaults to 10ms.
* @param capacity int maximum size for the LRU cache.
*/
public LRUCache(int capacity) {
this(capacity, 10);
this(capacity, 10, defaultScheduler, ForkJoinPool.commonPool());
isDefaultScheduler = true;
}

/**
* Create a LRUCache with the maximum capacity of 'capacity.' Note, the LRUCache could temporarily exceed the
* capacity, however, it will quickly reduce to that amount. This time is configurable via the cleanupDelay
* Create a LRUCache with the maximum capacity of 'capacity.' Note, the LRUCache could temporarily exceed the
* capacity, however, it will quickly reduce to that amount. This time is configurable via the cleanupDelay
* parameter.
*
* @param capacity int maximum size for the LRU cache.
* @param cleanupDelayMillis int milliseconds before scheduling a cleanup (reduction to capacity if the cache currently
* exceeds it).
*/
public LRUCache(int capacity, int cleanupDelayMillis) {
this(capacity, cleanupDelayMillis, defaultScheduler, ForkJoinPool.commonPool());
isDefaultScheduler = true;
}

/**
* Create a LRUCache with the maximum capacity of 'capacity.' Note, the LRUCache could temporarily exceed the
* capacity, however, it will quickly reduce to that amount. This time is configurable via the cleanupDelay
* parameter and custom scheduler and executor services.
* @param capacity int maximum size for the LRU cache.
* @param cleanupDelayMillis int milliseconds before scheduling a cleanup (reduction to capacity if the cache currently
* exceeds it).
* @param scheduler ScheduledExecutorService for scheduling cleanup tasks.
* @param cleanupExecutor ExecutorService for executing cleanup tasks.
*/
public LRUCache(int capacity, int cleanupDelayMillis, ScheduledExecutorService scheduler, ExecutorService cleanupExecutor) {
this.capacity = capacity;
this.cache = new ConcurrentHashMap<>(capacity);
this.cleanupDelayMillis = cleanupDelayMillis;
this.scheduler = scheduler;
this.cleanupExecutor = cleanupExecutor;
isDefaultScheduler = false;
}

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -130,7 +152,7 @@ public V put(K key, V value) {
if (oldNode != null) {
newNode.updateTimestamp();
return fromCacheItem(oldNode.value);
} else if (cache.size() > capacity) {
} else if (size() > capacity) {
scheduleCleanup();
}
return null;
Expand Down Expand Up @@ -201,10 +223,8 @@ public Collection<V> values() {

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Map))
return false;
if (this == o) return true;
if (!(o instanceof Map)) return false;
Map<?, ?> other = (Map<?, ?>) o;
return entrySet().equals(other.entrySet());
}
Expand Down Expand Up @@ -239,7 +259,7 @@ public String toString() {
// Schedule a delayed cleanup
private void scheduleCleanup() {
if (cleanupScheduled.compareAndSet(false, true)) {
executorService.schedule(this::cleanup, cleanupDelayMillis, TimeUnit.MILLISECONDS);
scheduler.schedule(() -> cleanupExecutor.execute(this::cleanup), cleanupDelayMillis, TimeUnit.MILLISECONDS);
}
}

Expand All @@ -253,4 +273,13 @@ private Object toCacheItem(Object item) {
private <T> T fromCacheItem(Object cacheItem) {
return cacheItem == NULL_ITEM ? null : (T) cacheItem;
}

/**
* Shut down the scheduler if it is the default one.
*/
public void shutdown() {
if (isDefaultScheduler) {
scheduler.shutdown();
}
}
}
12 changes: 12 additions & 0 deletions src/test/java/com/cedarsoftware/util/LRUCacheTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -459,4 +459,16 @@ void testNullKeyValue()
cache2.put(null, null);
assert cache1.equals(cache2);
}

@Test
void testSpeed()
{
long startTime = System.currentTimeMillis();
LRUCache<Integer, Boolean> cache = new LRUCache<>(30000000);
for (int i = 0; i < 30000000; i++) {
cache.put(i, true);
}
long endTime = System.currentTimeMillis();
System.out.println("Speed: " + (endTime - startTime));
}
}

0 comments on commit 2d5e69f

Please sign in to comment.