diff --git a/src/main/java/br/ufrgs/inf/prosoft/cache/MultiCache.java b/src/main/java/br/ufrgs/inf/prosoft/cache/MultiCache.java
index ab1b242..702a450 100644
--- a/src/main/java/br/ufrgs/inf/prosoft/cache/MultiCache.java
+++ b/src/main/java/br/ufrgs/inf/prosoft/cache/MultiCache.java
@@ -29,6 +29,7 @@ public class MultiCache<K, V> implements Cache<K, V> {
private final HashMap<K, V> map;
private final ConcurrentHashMap<Optional<K>, Long> keyHasTTL;
private final CachePerformance cachePerformance;
+ private ScheduledExecutorService batchEntriesInvalidator;
public MultiCache() {
this(new CachePerformance());
@@ -42,15 +43,6 @@ public class MultiCache<K, V> implements Cache<K, V> {
this.cachePerformance = cachingPerformance;
this.map = new HashMap<>();
this.keyHasTTL = new ConcurrentHashMap<>();
-
- ScheduledExecutorService batchEntriesInvalidator = Executors.newScheduledThreadPool(1);
- batchEntriesInvalidator.scheduleAtFixedRate(() -> {
- this.keyHasTTL.forEach((key, value) -> {
- if (!isValid(key.orElse(null))) {
- invalidate(key.orElse(null));
- }
- });
- }, 10, 10, TimeUnit.SECONDS);
}
public CachePerformance getCachePerformance() {
@@ -61,6 +53,20 @@ public class MultiCache<K, V> implements Cache<K, V> {
public void put(K key, V value, long timeToLive) {
put(key, value);
this.keyHasTTL.put(Optional.ofNullable(key), System.currentTimeMillis() + timeToLive);
+ if (batchEntriesInvalidator == null) {
+ batchEntriesInvalidator = Executors.newScheduledThreadPool(0);
+ batchEntriesInvalidator.scheduleAtFixedRate(() -> {
+ this.keyHasTTL.forEach((k, v) -> {
+ if (!isValid(k.orElse(null))) {
+ invalidate(k.orElse(null));
+ }
+ });
+ if (this.keyHasTTL.isEmpty()) {
+ this.batchEntriesInvalidator.shutdown();
+ this.batchEntriesInvalidator = null;
+ }
+ }, 10, 10, TimeUnit.SECONDS);
+ }
}
@Override