Skip to content

Apache Lucene open-source search software

SOLR-9658: Max idle time support for SolrCache implementations.

Andrzej Bialeckie04917dc9f66
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 4e27e266091..dc7105ec59f 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -159,6 +159,8 @@ Improvements
* SOLR-13739: Optimized large managed schema modifications; Internal O(n^2) problem. (Thomas Wöckinger via David Smiley)
+* SOLR-9658: Max idle time support for SolrCache implementations. (hoss, ab)
+
Bug Fixes
----------------------
diff --git a/solr/core/src/java/org/apache/solr/search/FastLRUCache.java b/solr/core/src/java/org/apache/solr/search/FastLRUCache.java
index dee2e40faa1..1cec0aa7d58 100644
--- a/solr/core/src/java/org/apache/solr/search/FastLRUCache.java
+++ b/solr/core/src/java/org/apache/solr/search/FastLRUCache.java
@@ -73,6 +73,7 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
private int initialSize;
private int acceptableSize;
private boolean cleanupThread;
+ private int maxIdleTimeSec;
private long ramLowerWatermark;
private MetricsMap cacheMap;
@@ -109,17 +110,24 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
str = (String) args.get(SHOW_ITEMS_PARAM);
showItems = str == null ? 0 : Integer.parseInt(str);
+ str = (String) args.get(MAX_IDLE_TIME_PARAM);
+ if (str == null) {
+ maxIdleTimeSec = -1;
+ } else {
+ maxIdleTimeSec = Integer.parseInt(str);
+ }
+
str = (String) args.get(MAX_RAM_MB_PARAM);
long maxRamMB = str == null ? -1 : (long) Double.parseDouble(str);
this.maxRamBytes = maxRamMB < 0 ? Long.MAX_VALUE : maxRamMB * 1024L * 1024L;
if (maxRamBytes != Long.MAX_VALUE) {
ramLowerWatermark = Math.round(maxRamBytes * 0.8);
description = generateDescription(maxRamBytes, ramLowerWatermark, cleanupThread);
- cache = new ConcurrentLRUCache<>(ramLowerWatermark, maxRamBytes, cleanupThread, null);
+ cache = new ConcurrentLRUCache<>(ramLowerWatermark, maxRamBytes, cleanupThread, null, maxIdleTimeSec);
} else {
ramLowerWatermark = -1L;
description = generateDescription(maxSize, initialSize, minSizeLimit, acceptableSize, cleanupThread);
- cache = new ConcurrentLRUCache<>(maxSize, minSizeLimit, acceptableSize, initialSize, cleanupThread, false, null);
+ cache = new ConcurrentLRUCache<>(maxSize, minSizeLimit, acceptableSize, initialSize, cleanupThread, false, null, maxIdleTimeSec);
}
cache.setAlive(false);
@@ -257,11 +265,13 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
long hits = stats.getCumulativeHits();
long inserts = stats.getCumulativePuts();
long evictions = stats.getCumulativeEvictions();
+ long idleEvictions = stats.getCumulativeIdleEvictions();
long size = stats.getCurrentSize();
long clookups = 0;
long chits = 0;
long cinserts = 0;
long cevictions = 0;
+ long cIdleEvictions = 0;
// NOTE: It is safe to iterate on a CopyOnWriteArrayList
for (ConcurrentLRUCache.Stats statistiscs : statsList) {
@@ -269,6 +279,7 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
chits += statistiscs.getCumulativeHits();
cinserts += statistiscs.getCumulativePuts();
cevictions += statistiscs.getCumulativeEvictions();
+ cIdleEvictions += statistiscs.getCumulativeIdleEvictions();
}
map.put(LOOKUPS_PARAM, lookups);
@@ -278,6 +289,7 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
map.put(EVICTIONS_PARAM, evictions);
map.put(SIZE_PARAM, size);
map.put("cleanupThread", cleanupThread);
+ map.put("idleEvictions", idleEvictions);
map.put(RAM_BYTES_USED_PARAM, ramBytesUsed());
map.put(MAX_RAM_MB_PARAM, getMaxRamMB());
@@ -287,6 +299,7 @@ public class FastLRUCache<K, V> extends SolrCacheBase implements SolrCache<K, V>
map.put("cumulative_hitratio", calcHitRatio(clookups, chits));
map.put("cumulative_inserts", cinserts);
map.put("cumulative_evictions", cevictions);
+ map.put("cumulative_idleEvictions", cIdleEvictions);
if (detailed && showItems != 0) {
Map items = cache.getLatestAccessedItems(showItems == -1 ? Integer.MAX_VALUE : showItems);
diff --git a/solr/core/src/java/org/apache/solr/search/LFUCache.java b/solr/core/src/java/org/apache/solr/search/LFUCache.java
index 48bd92c0473..b9a482025cf 100644
--- a/solr/core/src/java/org/apache/solr/search/LFUCache.java
+++ b/solr/core/src/java/org/apache/solr/search/LFUCache.java
@@ -76,6 +76,7 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
private ConcurrentLFUCache<K, V> cache;
private int showItems = 0;
private Boolean timeDecay = true;
+ private int maxIdleTimeSec;
private MetricsMap cacheMap;
private Set<String> metricNames = ConcurrentHashMap.newKeySet();
private MetricRegistry registry;
@@ -124,9 +125,16 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
str = (String) args.get(TIME_DECAY_PARAM);
timeDecay = (str == null) || Boolean.parseBoolean(str);
+ str = (String) args.get(MAX_IDLE_TIME_PARAM);
+ if (str == null) {
+ maxIdleTimeSec = -1;
+ } else {
+ maxIdleTimeSec = Integer.parseInt(str);
+ }
description = generateDescription();
- cache = new ConcurrentLFUCache<>(maxSize, minSizeLimit, acceptableSize, initialSize, cleanupThread, false, null, timeDecay);
+ cache = new ConcurrentLFUCache<>(maxSize, minSizeLimit, acceptableSize, initialSize,
+ cleanupThread, false, null, timeDecay, maxIdleTimeSec);
cache.setAlive(false);
statsList = (List<ConcurrentLFUCache.Stats>) persistence;
@@ -146,7 +154,8 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
private String generateDescription() {
String descr = "Concurrent LFU Cache(maxSize=" + maxSize + ", initialSize=" + initialSize +
", minSize=" + minSizeLimit + ", acceptableSize=" + acceptableSize + ", cleanupThread=" + cleanupThread +
- ", timeDecay=" + timeDecay;
+ ", timeDecay=" + timeDecay +
+ ", maxIdleTime=" + maxIdleTimeSec;
if (autowarmCount > 0) {
descr += ", autowarmCount=" + autowarmCount + ", regenerator=" + regenerator;
}
@@ -263,6 +272,7 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
long hits = stats.getCumulativeHits();
long inserts = stats.getCumulativePuts();
long evictions = stats.getCumulativeEvictions();
+ long idleEvictions = stats.getCumulativeIdleEvictions();
long size = stats.getCurrentSize();
map.put(LOOKUPS_PARAM, lookups);
@@ -278,7 +288,9 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
map.put(CLEANUP_THREAD_PARAM, cleanupThread);
map.put(SHOW_ITEMS_PARAM, showItems);
map.put(TIME_DECAY_PARAM, timeDecay);
-
+ map.put(RAM_BYTES_USED_PARAM, ramBytesUsed());
+ map.put(MAX_IDLE_TIME_PARAM, maxIdleTimeSec);
+ map.put("idleEvictions", idleEvictions);
map.put("warmupTime", warmupTime);
@@ -286,6 +298,7 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
long chits = 0;
long cinserts = 0;
long cevictions = 0;
+ long cidleEvictions = 0;
// NOTE: It is safe to iterate on a CopyOnWriteArrayList
for (ConcurrentLFUCache.Stats statistics : statsList) {
@@ -293,13 +306,14 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
chits += statistics.getCumulativeHits();
cinserts += statistics.getCumulativePuts();
cevictions += statistics.getCumulativeEvictions();
+ cidleEvictions += statistics.getCumulativeIdleEvictions();
}
map.put("cumulative_lookups", clookups);
map.put("cumulative_hits", chits);
map.put("cumulative_hitratio", calcHitRatio(clookups, chits));
map.put("cumulative_inserts", cinserts);
map.put("cumulative_evictions", cevictions);
- map.put(RAM_BYTES_USED_PARAM, ramBytesUsed());
+ map.put("cumulative_idleEvictions", cidleEvictions);
if (detailed && showItems != 0) {
Map items = cache.getMostUsedItems(showItems == -1 ? Integer.MAX_VALUE : showItems);
@@ -388,5 +402,4 @@ public class LFUCache<K, V> implements SolrCache<K, V>, Accountable {
}
}
}
-
}
diff --git a/solr/core/src/java/org/apache/solr/search/LRUCache.java b/solr/core/src/java/org/apache/solr/search/LRUCache.java
index a76fefa89ed..bcb56cfea0e 100644
--- a/solr/core/src/java/org/apache/solr/search/LRUCache.java
+++ b/solr/core/src/java/org/apache/solr/search/LRUCache.java
@@ -31,6 +31,7 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Accountables;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.util.TimeSource;
import org.apache.solr.metrics.MetricsMap;
import org.apache.solr.metrics.SolrMetricManager;
import org.slf4j.Logger;
@@ -56,6 +57,7 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
LongAdder inserts = new LongAdder();
LongAdder evictions = new LongAdder();
LongAdder evictionsRamUsage = new LongAdder();
+ LongAdder evictionsIdleTime = new LongAdder();
}
private CumulativeStats stats;
@@ -67,10 +69,11 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
private long inserts;
private long evictions;
private long evictionsRamUsage;
+ private long evictionsIdleTime;
private long warmupTime = 0;
- private Map<K,V> map;
+ private Map<K, CacheValue<V>> map;
private String description="LRU Cache";
private MetricsMap cacheMap;
private Set<String> metricNames = ConcurrentHashMap.newKeySet();
@@ -79,9 +82,34 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
private int initialSize;
private long maxRamBytes = Long.MAX_VALUE;
+ private long maxIdleTimeNs;
+ private final TimeSource timeSource = TimeSource.NANO_TIME;
+ private long oldestEntry = 0L;
+ // for unit testing
+ private boolean syntheticEntries = false;
+
// The synchronization used for the map will be used to update this,
// hence not an AtomicLong
- private long ramBytesUsed = 0;
+ private long ramBytesUsed = 0L;
+
+ public static final class CacheValue<V> implements Accountable {
+ public static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(CacheValue.class);
+ final long ramBytesUsed;
+ public final long createTime;
+ public final V value;
+
+ public CacheValue(V value, long createTime) {
+ this.value = value;
+ this.createTime = createTime;
+ ramBytesUsed = BASE_RAM_BYTES_USED +
+ RamUsageEstimator.sizeOfObject(value, QUERY_DEFAULT_RAM_BYTES_USED);
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return ramBytesUsed;
+ }
+ }
@Override
public Object init(Map args, Object persistence, CacheRegenerator regenerator) {
@@ -92,15 +120,63 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
initialSize = Math.min(str==null ? 1024 : Integer.parseInt(str), maxSize);
str = (String) args.get(MAX_RAM_MB_PARAM);
this.maxRamBytes = str == null ? Long.MAX_VALUE : (long) (Double.parseDouble(str) * 1024L * 1024L);
+ str = (String) args.get(MAX_IDLE_TIME_PARAM);
+ if (str == null) {
+ maxIdleTimeNs = Long.MAX_VALUE;
+ } else {
+ int maxIdleTime = Integer.parseInt(str);
+ if (maxIdleTime > 0) {
+ maxIdleTimeNs = TimeUnit.NANOSECONDS.convert(Integer.parseInt(str), TimeUnit.SECONDS);
+ } else {
+ maxIdleTimeNs = Long.MAX_VALUE;
+ }
+ }
description = generateDescription();
- map = new LinkedHashMap<K,V>(initialSize, 0.75f, true) {
+ map = new LinkedHashMap<K, CacheValue<V>>(initialSize, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
+ // remove items older than maxIdleTimeNs
+ if (maxIdleTimeNs != Long.MAX_VALUE) {
+ long idleCutoff = timeSource.getEpochTimeNs() - maxIdleTimeNs;
+ if (oldestEntry < idleCutoff) {
+ long currentOldestEntry = Long.MAX_VALUE;
+ Iterator<Map.Entry<K, CacheValue<V>>> iterator = entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<K, CacheValue<V>> entry = iterator.next();
+ if (entry.getValue().createTime < idleCutoff) {
+ long bytesToDecrement = RamUsageEstimator.sizeOfObject(entry.getKey(), QUERY_DEFAULT_RAM_BYTES_USED);
+ bytesToDecrement += RamUsageEstimator.sizeOfObject(entry.getValue(), QUERY_DEFAULT_RAM_BYTES_USED);
+ bytesToDecrement += LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY;
+ ramBytesUsed -= bytesToDecrement;
+ iterator.remove();
+ evictions++;
+ evictionsIdleTime++;
+ stats.evictionsIdleTime.increment();
+ stats.evictions.increment();
+ } else {
+ if (syntheticEntries) {
+ // no guarantee on the actual create time - make a full sweep
+ if (currentOldestEntry > entry.getValue().createTime) {
+ currentOldestEntry = entry.getValue().createTime;
+ }
+ } else {
+ // iterator is sorted by insertion order (and time)
+ // so we can quickly terminate the sweep
+ currentOldestEntry = entry.getValue().createTime;
+ break;
+ }
+ }
+ }
+ if (currentOldestEntry != Long.MAX_VALUE) {
+ oldestEntry = currentOldestEntry;
+ }
+ }
+ }
if (ramBytesUsed > getMaxRamBytes()) {
- Iterator<Map.Entry<K, V>> iterator = entrySet().iterator();
+ Iterator<Map.Entry<K, CacheValue<V>>> iterator = entrySet().iterator();
do {
- Map.Entry<K, V> entry = iterator.next();
+ Map.Entry<K, CacheValue<V>> entry = iterator.next();
long bytesToDecrement = RamUsageEstimator.sizeOfObject(entry.getKey(), QUERY_DEFAULT_RAM_BYTES_USED);
bytesToDecrement += RamUsageEstimator.sizeOfObject(entry.getValue(), QUERY_DEFAULT_RAM_BYTES_USED);
bytesToDecrement += LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY;
@@ -111,13 +187,10 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
stats.evictions.increment();
stats.evictionsRamUsage.increment();
} while (iterator.hasNext() && ramBytesUsed > getMaxRamBytes());
- // must return false according to javadocs of removeEldestEntry if we're modifying
- // the map ourselves
- return false;
} else if (size() > getMaxSize()) {
- Iterator<Map.Entry<K, V>> iterator = entrySet().iterator();
+ Iterator<Map.Entry<K, CacheValue<V>>> iterator = entrySet().iterator();
do {
- Map.Entry<K, V> entry = iterator.next();
+ Map.Entry<K, CacheValue<V>> entry = iterator.next();
long bytesToDecrement = RamUsageEstimator.sizeOfObject(entry.getKey(), QUERY_DEFAULT_RAM_BYTES_USED);
bytesToDecrement += RamUsageEstimator.sizeOfObject(entry.getValue(), QUERY_DEFAULT_RAM_BYTES_USED);
bytesToDecrement += LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY;
@@ -129,11 +202,9 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
evictions++;
stats.evictions.increment();
} while (iterator.hasNext() && size() > getMaxSize());
- // must return false according to javadocs of removeEldestEntry if we're modifying
- // the map ourselves
- return false;
}
- // neither size nor RAM exceeded - ok to keep the entry
+ // must return false according to javadocs of removeEldestEntry if we're modifying
+ // the map ourselves
return false;
}
};
@@ -148,6 +219,16 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
return persistence;
}
+ /**
+ * Visible for testing. This flag tells the eviction code that (unlike with real entries)
+ * there's no guarantee on the order of entries being inserted with monotonically ascending creation
+ * time. Setting this to true causes a full sweep when looking for entries to evict.
+ * @lucene.internal
+ */
+ public void setSyntheticEntries(boolean syntheticEntries) {
+ this.syntheticEntries = syntheticEntries;
+ }
+
public long getMaxRamBytes() {
return maxRamBytes;
}
@@ -164,6 +245,9 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
if (getMaxRamBytes() != Long.MAX_VALUE) {
description += ", maxRamMB=" + (getMaxRamBytes() / 1024L / 1024L);
}
+ if (maxIdleTimeNs != Long.MAX_VALUE) {
+ description += ", " + MAX_IDLE_TIME_PARAM + "=" + TimeUnit.SECONDS.convert(maxIdleTimeNs, TimeUnit.NANOSECONDS);
+ }
description += ')';
return description;
}
@@ -180,20 +264,35 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
if (maxSize == Integer.MAX_VALUE && maxRamBytes == Long.MAX_VALUE) {
throw new IllegalStateException("Cache: " + getName() + " has neither size nor RAM limit!");
}
+ CacheValue<V> cacheValue = new CacheValue<>(value, timeSource.getEpochTimeNs());
+ return putCacheValue(key, cacheValue);
+ }
+
+ /**
+ * Visible for testing to create synthetic cache entries.
+ * @lucene.internal
+ */
+ public V putCacheValue(K key, CacheValue<V> cacheValue) {
synchronized (map) {
if (getState() == State.LIVE) {
stats.inserts.increment();
}
+ if (syntheticEntries) {
+ if (cacheValue.createTime < oldestEntry) {
+ oldestEntry = cacheValue.createTime;
+ }
+ }
+
// increment local inserts regardless of state???
// it does make it more consistent with the current size...
inserts++;
// important to calc and add new ram bytes first so that removeEldestEntry can compare correctly
long keySize = RamUsageEstimator.sizeOfObject(key, QUERY_DEFAULT_RAM_BYTES_USED);
- long valueSize = RamUsageEstimator.sizeOfObject(value, QUERY_DEFAULT_RAM_BYTES_USED);
+ long valueSize = RamUsageEstimator.sizeOfObject(cacheValue, QUERY_DEFAULT_RAM_BYTES_USED);
ramBytesUsed += keySize + valueSize + LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY;
- V old = map.put(key, value);
+ CacheValue<V> old = map.put(key, cacheValue);
if (old != null) {
long bytesToDecrement = RamUsageEstimator.sizeOfObject(old, QUERY_DEFAULT_RAM_BYTES_USED);
// the key existed in the map but we added its size before the put, so let's back out
@@ -201,14 +300,14 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
bytesToDecrement += RamUsageEstimator.sizeOfObject(key, QUERY_DEFAULT_RAM_BYTES_USED);
ramBytesUsed -= bytesToDecrement;
}
- return old;
+ return old == null ? null : old.value;
}
}
@Override
public V get(K key) {
synchronized (map) {
- V val = map.get(key);
+ CacheValue<V> val = map.get(key);
if (getState() == State.LIVE) {
// only increment lookups and hits if we are live.
lookups++;
@@ -218,7 +317,7 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
stats.hits.increment();
}
}
- return val;
+ return val == null ? null : val.value;
}
}
@@ -248,7 +347,7 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
keys = new Object[sz];
vals = new Object[sz];
- Iterator<Map.Entry<K, V>> iter = other.map.entrySet().iterator();
+ Iterator<Map.Entry<K, CacheValue<V>>> iter = other.map.entrySet().iterator();
// iteration goes from oldest (least recently used) to most recently used,
// so we need to skip over the oldest entries.
@@ -257,9 +356,9 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
for (int i=0; i<sz; i++) {
- Map.Entry<K,V> entry = iter.next();
+ Map.Entry<K, CacheValue<V>> entry = iter.next();
keys[i]=entry.getKey();
- vals[i]=entry.getValue();
+ vals[i]=entry.getValue().value;
}
}
@@ -316,7 +415,10 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
res.put(RAM_BYTES_USED_PARAM, ramBytesUsed());
res.put(MAX_RAM_MB_PARAM, getMaxRamMB());
res.put(MAX_SIZE_PARAM, maxSize);
+ res.put(MAX_IDLE_TIME_PARAM, maxIdleTimeNs != Long.MAX_VALUE ?
+ TimeUnit.SECONDS.convert(maxIdleTimeNs, TimeUnit.NANOSECONDS) : -1);
res.put("evictionsRamUsage", evictionsRamUsage);
+ res.put("evictionsIdleTime", evictionsIdleTime);
}
res.put("warmupTime", warmupTime);
@@ -328,6 +430,7 @@ public class LRUCache<K,V> extends SolrCacheBase implements SolrCache<K,V>, Acco
res.put("cumulative_inserts", stats.inserts.longValue());
res.put("cumulative_evictions", stats.evictions.longValue());
res.put("cumulative_evictionsRamUsage", stats.evictionsRamUsage.longValue());
+ res.put("cumulative_evictionsIdleTime", stats.evictionsIdleTime.longValue());
});
manager.registerGauge(this, registryName, cacheMap, tag, true, scope, getCategory().toString());
}
diff --git a/solr/core/src/java/org/apache/solr/search/SolrCache.java b/solr/core/src/java/org/apache/solr/search/SolrCache.java
index b4817f5c36b..9fe186a1a23 100644
--- a/solr/core/src/java/org/apache/solr/search/SolrCache.java
+++ b/solr/core/src/java/org/apache/solr/search/SolrCache.java
@@ -37,6 +37,7 @@ public interface SolrCache<K,V> extends SolrInfoBean, SolrMetricProducer {
String MAX_SIZE_PARAM = "maxSize";
String RAM_BYTES_USED_PARAM = "ramBytesUsed";
String MAX_RAM_MB_PARAM = "maxRamMB";
+ String MAX_IDLE_TIME_PARAM = "maxIdleTime";
/**
* The initialization routine. Instance specific arguments are passed in
@@ -124,7 +125,6 @@ public interface SolrCache<K,V> extends SolrInfoBean, SolrMetricProducer {
*/
State getState();
-
/**
* Warm this cache associated with <code>searcher</code> using the <code>old</code>
* cache object. <code>this</code> and <code>old</code> will have the same concrete type.
diff --git a/solr/core/src/java/org/apache/solr/util/ConcurrentLFUCache.java b/solr/core/src/java/org/apache/solr/util/ConcurrentLFUCache.java
index de72e90e610..3aca5d572ab 100644
--- a/solr/core/src/java/org/apache/solr/util/ConcurrentLFUCache.java
+++ b/solr/core/src/java/org/apache/solr/util/ConcurrentLFUCache.java
@@ -17,10 +17,12 @@
package org.apache.solr.util;
import java.lang.ref.WeakReference;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
@@ -28,6 +30,7 @@ import java.util.concurrent.locks.ReentrantLock;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.solr.common.util.Cache;
+import org.apache.solr.common.util.TimeSource;
import static org.apache.lucene.util.RamUsageEstimator.HASHTABLE_RAM_BYTES_PER_ENTRY;
import static org.apache.lucene.util.RamUsageEstimator.QUERY_DEFAULT_RAM_BYTES_USED;
@@ -63,11 +66,21 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
private final EvictionListener<K, V> evictionListener;
private CleanupThread cleanupThread;
private boolean timeDecay;
+ private long maxIdleTimeNs;
+ private final TimeSource timeSource = TimeSource.NANO_TIME;
+ private final AtomicLong oldestEntry = new AtomicLong(0L);
private final AtomicLong ramBytes = new AtomicLong(0);
public ConcurrentLFUCache(int upperWaterMark, final int lowerWaterMark, int acceptableSize,
int initialSize, boolean runCleanupThread, boolean runNewThreadForCleanup,
EvictionListener<K, V> evictionListener, boolean timeDecay) {
+ this(upperWaterMark, lowerWaterMark, acceptableSize, initialSize, runCleanupThread,
+ runNewThreadForCleanup, evictionListener, timeDecay, -1);
+ }
+
+ public ConcurrentLFUCache(int upperWaterMark, final int lowerWaterMark, int acceptableSize,
+ int initialSize, boolean runCleanupThread, boolean runNewThreadForCleanup,
+ EvictionListener<K, V> evictionListener, boolean timeDecay, int maxIdleTimeSec) {
setUpperWaterMark(upperWaterMark);
setLowerWaterMark(lowerWaterMark);
setAcceptableWaterMark(acceptableSize);
@@ -75,12 +88,13 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
this.evictionListener = evictionListener;
setNewThreadForCleanup(runNewThreadForCleanup);
setTimeDecay(timeDecay);
+ setMaxIdleTime(maxIdleTimeSec);
setRunCleanupThread(runCleanupThread);
}
public ConcurrentLFUCache(int size, int lowerWatermark) {
this(size, lowerWatermark, (int) Math.floor((lowerWatermark + size) / 2),
- (int) Math.ceil(0.75 * size), false, false, null, true);
+ (int) Math.ceil(0.75 * size), false, false, null, true, -1);
}
public void setAlive(boolean live) {
@@ -106,13 +120,25 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
this.timeDecay = timeDecay;
}
+ public void setMaxIdleTime(int maxIdleTime) {
+ long oldMaxIdleTimeNs = maxIdleTimeNs;
+ maxIdleTimeNs = maxIdleTime > 0 ? TimeUnit.NANOSECONDS.convert(maxIdleTime, TimeUnit.SECONDS) : Long.MAX_VALUE;
+ if (cleanupThread != null && maxIdleTimeNs < oldMaxIdleTimeNs) {
+ cleanupThread.wakeThread();
+ }
+ }
+
public synchronized void setNewThreadForCleanup(boolean newThreadForCleanup) {
this.newThreadForCleanup = newThreadForCleanup;
+ if (newThreadForCleanup) {
+ setRunCleanupThread(false);
+ }
}
public synchronized void setRunCleanupThread(boolean runCleanupThread) {
this.runCleanupThread = runCleanupThread;
if (this.runCleanupThread) {
+ newThreadForCleanup = false;
if (cleanupThread == null) {
cleanupThread = new CleanupThread(this);
cleanupThread.start();
@@ -130,13 +156,12 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
CacheEntry<K, V> e = map.get(key);
if (e == null) {
if (islive) stats.missCounter.incrementAndGet();
- return null;
- }
- if (islive) {
- e.lastAccessed = stats.accessCounter.incrementAndGet();
+ } else if (islive) {
+ e.lastAccessed = timeSource.getEpochTimeNs();
+ stats.accessCounter.incrementAndGet();
e.hits.incrementAndGet();
}
- return e.value;
+ return e != null ? e.value : null;
}
@Override
@@ -153,8 +178,19 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
@Override
public V put(K key, V val) {
if (val == null) return null;
- CacheEntry<K, V> e = new CacheEntry<>(key, val, stats.accessCounter.incrementAndGet());
- CacheEntry<K, V> oldCacheEntry = map.put(key, e);
+ CacheEntry<K, V> e = new CacheEntry<>(key, val, timeSource.getEpochTimeNs());
+ return putCacheEntry(e);
+ }
+
+ /**
+ * Visible for testing to create synthetic cache entries.
+ * @lucene.internal
+ */
+ public V putCacheEntry(CacheEntry<K, V> e) {
+ stats.accessCounter.incrementAndGet();
+ // initialize oldestEntry
+ oldestEntry.updateAndGet(x -> x > e.lastAccessed || x == 0 ? e.lastAccessed : x);
+ CacheEntry<K, V> oldCacheEntry = map.put(e.key, e);
int currentSize;
if (oldCacheEntry == null) {
currentSize = stats.size.incrementAndGet();
@@ -180,7 +216,9 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
//
// Thread safety note: isCleaning read is piggybacked (comes after) other volatile reads
// in this method.
- if (currentSize > upperWaterMark && !isCleaning) {
+ boolean evictByIdleTime = maxIdleTimeNs != Long.MAX_VALUE;
+ long idleCutoff = evictByIdleTime ? timeSource.getEpochTimeNs() - maxIdleTimeNs : -1L;
+ if ((currentSize > upperWaterMark || (evictByIdleTime && oldestEntry.get() < idleCutoff)) && !isCleaning) {
if (newThreadForCleanup) {
new Thread(this::markAndSweep).start();
} else if (cleanupThread != null) {
@@ -194,8 +232,10 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
/**
* Removes items from the cache to bring the size down to the lowerWaterMark.
+ * <p>Visible for unit testing.</p>
+ * @lucene.internal
*/
- private void markAndSweep() {
+ public void markAndSweep() {
if (!markAndSweepLock.tryLock()) return;
try {
long lowHitCount = this.lowHitCount;
@@ -203,18 +243,47 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
this.lowHitCount = lowHitCount; // volatile write to make isCleaning visible
int sz = stats.size.get();
- if (sz <= upperWaterMark) {
+ boolean evictByIdleTime = maxIdleTimeNs != Long.MAX_VALUE;
+ long idleCutoff = evictByIdleTime ? timeSource.getEpochTimeNs() - maxIdleTimeNs : -1L;
+ if (sz <= upperWaterMark && (evictByIdleTime && oldestEntry.get() > idleCutoff)) {
/* SOLR-7585: Even though we acquired a lock, multiple threads might detect a need for calling this method.
* Locking keeps these from executing at the same time, so they run sequentially. The second and subsequent
* sequential runs of this method don't need to be done, since there are no elements to remove.
*/
return;
}
-
+
+ // first evict by idleTime - it's less costly to do an additional pass over the
+ // map than to manage the outdated entries in a TreeSet
+ if (evictByIdleTime) {
+ long currentOldestEntry = Long.MAX_VALUE;
+ Iterator<Map.Entry<Object, CacheEntry<K, V>>> iterator = map.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<Object, CacheEntry<K, V>> entry = iterator.next();
+ entry.getValue().lastAccessedCopy = entry.getValue().lastAccessed;
+ if (entry.getValue().lastAccessedCopy < idleCutoff) {
+ iterator.remove();
+ postRemoveEntry(entry.getValue());
+ stats.evictionIdleCounter.incrementAndGet();
+ } else {
+ if (entry.getValue().lastAccessedCopy < currentOldestEntry) {
+ currentOldestEntry = entry.getValue().lastAccessedCopy;
+ }
+ }
+ }
+ if (currentOldestEntry != Long.MAX_VALUE) {
+ oldestEntry.set(currentOldestEntry);
+ }
+ // refresh size and maybe return
+ sz = stats.size.get();
+ if (sz <= upperWaterMark) {
+ return;
+ }
+ }
int wantToRemove = sz - lowerWaterMark;
-
+
TreeSet<CacheEntry<K, V>> tree = new TreeSet<>();
-
+
for (CacheEntry<K, V> ce : map.values()) {
// set hitsCopy to avoid later Atomic reads. Primitive types are faster than the atomic get().
ce.hitsCopy = ce.hits.get();
@@ -222,7 +291,6 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
if (timeDecay) {
ce.hits.set(ce.hitsCopy >>> 1);
}
-
if (tree.size() < wantToRemove) {
tree.add(ce);
} else {
@@ -249,6 +317,18 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
for (CacheEntry<K, V> e : tree) {
evictEntry(e.key);
}
+ if (evictByIdleTime) {
+ // do a full pass because we don't what is the max. age of remaining items
+ long currentOldestEntry = Long.MAX_VALUE;
+ for (CacheEntry<K, V> e : map.values()) {
+ if (e.lastAccessedCopy < currentOldestEntry) {
+ currentOldestEntry = e.lastAccessedCopy;
+ }
+ }
+ if (currentOldestEntry != Long.MAX_VALUE) {
+ oldestEntry.set(currentOldestEntry);
+ }
+ }
} finally {
isCleaning = false; // set before markAndSweep.unlock() for visibility
markAndSweepLock.unlock();
@@ -257,6 +337,10 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
private void evictEntry(K key) {
CacheEntry<K, V> o = map.remove(key);
+ postRemoveEntry(o);
+ }
+
+ private void postRemoveEntry(CacheEntry<K, V> o) {
if (o == null) return;
ramBytes.addAndGet(-(o.ramBytesUsed() + HASHTABLE_RAM_BYTES_PER_ENTRY));
stats.size.decrementAndGet();
@@ -445,7 +529,7 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
public static class Stats implements Accountable {
private static final long RAM_BYTES_USED =
RamUsageEstimator.shallowSizeOfInstance(Stats.class) +
- 5 * RamUsageEstimator.primitiveSizes.get(long.class) +
+ 6 * RamUsageEstimator.primitiveSizes.get(long.class) +
RamUsageEstimator.primitiveSizes.get(int.class);
private final AtomicLong accessCounter = new AtomicLong(0),
@@ -454,6 +538,7 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
missCounter = new AtomicLong();
private final AtomicInteger size = new AtomicInteger();
private AtomicLong evictionCounter = new AtomicLong();
+ private AtomicLong evictionIdleCounter = new AtomicLong();
public long getCumulativeLookups() {
return (accessCounter.get() - putCounter.get() - nonLivePutCounter.get()) + missCounter.get();
@@ -471,6 +556,10 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
return evictionCounter.get();
}
+ public long getCumulativeIdleEvictions() {
+ return evictionIdleCounter.get();
+ }
+
public int getCurrentSize() {
return size.get();
}
@@ -489,6 +578,7 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
nonLivePutCounter.addAndGet(other.nonLivePutCounter.get());
missCounter.addAndGet(other.missCounter.get());
evictionCounter.addAndGet(other.evictionCounter.get());
+ evictionIdleCounter.addAndGet(other.evictionIdleCounter.get());
size.set(Math.max(size.get(), other.size.get()));
}
@@ -514,15 +604,18 @@ public class ConcurrentLFUCache<K, V> implements Cache<K,V>, Accountable {
@Override
public void run() {
while (true) {
+ ConcurrentLFUCache c = cache.get();
+ if(c == null) break;
synchronized (this) {
if (stop) break;
+ long waitTimeMs = c.maxIdleTimeNs != Long.MAX_VALUE ? TimeUnit.MILLISECONDS.convert(c.maxIdleTimeNs, TimeUnit.NANOSECONDS) : 0L;
try {
- this.wait();
+ this.wait(waitTimeMs);
} catch (InterruptedException e) {
}
}
if (stop) break;
- ConcurrentLFUCache c = cache.get();
+ c = cache.get();
if (c == null) break;
c.markAndSweep();
}
diff --git a/solr/core/src/java/org/apache/solr/util/ConcurrentLRUCache.java b/solr/core/src/java/org/apache/solr/util/ConcurrentLRUCache.java
index 80f8b833ca0..b6bf2a1d469 100644
--- a/solr/core/src/java/org/apache/solr/util/ConcurrentLRUCache.java
+++ b/solr/core/src/java/org/apache/solr/util/ConcurrentLRUCache.java
@@ -19,16 +19,19 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.solr.common.util.Cache;
+import org.apache.solr.common.util.TimeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
@@ -67,6 +70,9 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
private final Stats stats = new Stats();
private int acceptableWaterMark;
private long oldestEntry = 0; // not volatile, only accessed in the cleaning method
+ private final TimeSource timeSource = TimeSource.NANO_TIME;
+ private final AtomicLong oldestEntryNs = new AtomicLong(0);
+ private long maxIdleTimeNs;
private final EvictionListener<K,V> evictionListener;
private CleanupThread cleanupThread;
private boolean runCleanupThread;
@@ -76,6 +82,12 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
public ConcurrentLRUCache(long ramLowerWatermark, long ramUpperWatermark,
boolean runCleanupThread, EvictionListener<K, V> evictionListener) {
+ this(ramLowerWatermark, ramUpperWatermark, runCleanupThread, evictionListener, -1);
+ }
+
+ public ConcurrentLRUCache(long ramLowerWatermark, long ramUpperWatermark,
+ boolean runCleanupThread, EvictionListener<K, V> evictionListener,
+ int maxIdleTimeSec) {
this.ramLowerWatermark = ramLowerWatermark;
this.ramUpperWatermark = ramUpperWatermark;
@@ -87,12 +99,20 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
this.lowerWaterMark = Integer.MIN_VALUE;
this.upperWaterMark = Integer.MAX_VALUE;
+ setMaxIdleTime(maxIdleTimeSec);
setRunCleanupThread(runCleanupThread);
}
public ConcurrentLRUCache(int upperWaterMark, final int lowerWaterMark, int acceptableWatermark,
int initialSize, boolean runCleanupThread, boolean runNewThreadForCleanup,
EvictionListener<K,V> evictionListener) {
+ this(upperWaterMark, lowerWaterMark, acceptableWatermark, initialSize, runCleanupThread,
+ runNewThreadForCleanup, evictionListener, -1);
+ }
+
+ public ConcurrentLRUCache(int upperWaterMark, final int lowerWaterMark, int acceptableWatermark,
+ int initialSize, boolean runCleanupThread, boolean runNewThreadForCleanup,
+ EvictionListener<K,V> evictionListener, int maxIdleTimeSec) {
if (upperWaterMark < 1) throw new IllegalArgumentException("upperWaterMark must be > 0");
if (lowerWaterMark >= upperWaterMark)
throw new IllegalArgumentException("lowerWaterMark must be < upperWaterMark");
@@ -102,14 +122,15 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
this.lowerWaterMark = lowerWaterMark;
this.acceptableWaterMark = acceptableWatermark;
this.evictionListener = evictionListener;
- setRunCleanupThread(runCleanupThread);
this.ramLowerWatermark = Long.MIN_VALUE;
this.ramUpperWatermark = Long.MAX_VALUE;
+ setMaxIdleTime(maxIdleTimeSec);
+ setRunCleanupThread(runCleanupThread);
}
public ConcurrentLRUCache(int size, int lowerWatermark) {
this(size, lowerWatermark, (int) Math.floor((lowerWatermark + size) / 2),
- (int) Math.ceil(0.75 * size), false, false, null);
+ (int) Math.ceil(0.75 * size), false, false, null, -1);
}
public void setAlive(boolean live) {
@@ -143,6 +164,14 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
this.ramLowerWatermark = ramLowerWatermark;
}
+ public void setMaxIdleTime(int maxIdleTime) {
+ long oldMaxIdleTimeNs = maxIdleTimeNs;
+ maxIdleTimeNs = maxIdleTime > 0 ? TimeUnit.NANOSECONDS.convert(maxIdleTime, TimeUnit.SECONDS) : Long.MAX_VALUE;
+ if (cleanupThread != null && maxIdleTimeNs < oldMaxIdleTimeNs) {
+ cleanupThread.wakeThread();
+ }
+ }
+
public synchronized void setRunCleanupThread(boolean runCleanupThread) {
this.runCleanupThread = runCleanupThread;
if (this.runCleanupThread) {
@@ -183,8 +212,18 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
@Override
public V put(K key, V val) {
if (val == null) return null;
- CacheEntry<K,V> e = new CacheEntry<>(key, val, stats.accessCounter.incrementAndGet());
- CacheEntry<K,V> oldCacheEntry = map.put(key, e);
+ CacheEntry<K, V> e = new CacheEntry<>(key, val, timeSource.getEpochTimeNs(), stats.accessCounter.incrementAndGet());
+ return putCacheEntry(e);
+ }
+
+ /**
+ * Visible for testing to create synthetic cache entries.
+ * @lucene.internal
+ */
+ public V putCacheEntry(CacheEntry<K, V> e) {
+ // initialize oldestEntryNs
+ oldestEntryNs.updateAndGet(x -> x > e.createTime || x == 0 ? e.createTime : x);
+ CacheEntry<K,V> oldCacheEntry = map.put(e.key, e);
int currentSize;
if (oldCacheEntry == null) {
currentSize = stats.size.incrementAndGet();
@@ -210,7 +249,8 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
//
// Thread safety note: isCleaning read is piggybacked (comes after) other volatile reads
// in this method.
- if ((currentSize > upperWaterMark || ramBytes.get() > ramUpperWatermark) && !isCleaning) {
+ long idleCutoff = timeSource.getEpochTimeNs() - maxIdleTimeNs;
+ if ((currentSize > upperWaterMark || ramBytes.get() > ramUpperWatermark || oldestEntryNs.get() < idleCutoff) && !isCleaning) {
if (newThreadForCleanup) {
new Thread(this::markAndSweep).start();
} else if (cleanupThread != null){
@@ -224,16 +264,11 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
/**
* Removes items from the cache to bring the size down
- * to an acceptable value ('acceptableWaterMark').
- * <p/>
- * It is done in two stages. In the first stage, least recently used items are evicted.
- * If, after the first stage, the cache size is still greater than 'acceptableSize'
- * config parameter, the second stage takes over.
- * <p/>
- * The second stage is more intensive and tries to bring down the cache size
- * to the 'lowerWaterMark' config parameter.
+ * to an acceptable value.
+ * <p>Visible for unit testing.</p>
+ * @lucene.internal
*/
- private void markAndSweep() {
+ public void markAndSweep() {
// if we want to keep at least 1000 entries, then timestamps of
// current through current-1000 are guaranteed not to be the oldest (but that does
// not mean there are 1000 entries in that group... it's actually anywhere between
@@ -244,6 +279,12 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
if (!markAndSweepLock.tryLock()) return;
try {
+ if (maxIdleTimeNs != Long.MAX_VALUE) {
+ long idleCutoff = timeSource.getEpochTimeNs() - maxIdleTimeNs;
+ if (oldestEntryNs.get() < idleCutoff) {
+ markAndSweepByIdleTime();
+ }
+ }
if (upperWaterMark < size()) {
markAndSweepByCacheSize();
} else if (ramUpperWatermark < ramBytesUsed()) {
@@ -259,9 +300,35 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
}
/*
- Must be called after acquiring markAndSweeoLock
+ Must be called after acquiring markAndSweepLock
+ */
+ private void markAndSweepByIdleTime() {
+ assert markAndSweepLock.isHeldByCurrentThread() : "markAndSweepLock held by another thread";
+ Iterator<Map.Entry<Object, CacheEntry<K, V>>> iterator = map.entrySet().iterator();
+ long idleCutoff = timeSource.getEpochTimeNs() - maxIdleTimeNs;
+ long currentOldestEntry = Long.MAX_VALUE;
+ while (iterator.hasNext()) {
+ Map.Entry<Object, CacheEntry<K, V>> entry = iterator.next();
+ if (entry.getValue().createTime < idleCutoff) {
+ iterator.remove();
+ stats.evictionIdleCounter.incrementAndGet();
+ postRemoveEntry(entry.getValue());
+ } else {
+ if (entry.getValue().createTime < currentOldestEntry) {
+ currentOldestEntry = entry.getValue().createTime;
+ }
+ }
+ }
+ if (currentOldestEntry != Long.MAX_VALUE) {
+ oldestEntryNs.set(currentOldestEntry);
+ }
+ }
+
+ /*
+ Must be called after acquiring markAndSweepLock
*/
private void markAndSweepByRamSize() {
+ assert markAndSweepLock.isHeldByCurrentThread() : "markAndSweepLock held by another thread";
List<CacheEntry<K, V>> entriesInAccessOrder = new ArrayList<>(map.size());
map.forEach((o, kvCacheEntry) -> {
kvCacheEntry.lastAccessedCopy = kvCacheEntry.lastAccessed; // important because we want to avoid volatile read during comparisons
@@ -281,9 +348,19 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
}
/*
- Must be called after acquiring markAndSweeoLock
+ * Removes items from the cache to bring the size down
+ * to an acceptable value ('acceptableWaterMark').
+ * <p>
+ * It is done in two stages. In the first stage, least recently used items are evicted.
+ * If, after the first stage, the cache size is still greater than 'acceptableSize'
+ * config parameter, the second stage takes over.
+ * </p>
+ * <p>The second stage is more intensive and tries to bring down the cache size
+ * to the 'lowerWaterMark' config parameter.</p>
+ * Must be called after acquiring markAndSweepLock
*/
private void markAndSweepByCacheSize() {
+ assert markAndSweepLock.isHeldByCurrentThread() : "markAndSweepLock held by another thread";
long oldestEntry = this.oldestEntry;
isCleaning = true;
this.oldestEntry = oldestEntry; // volatile write to make isCleaning visible
@@ -503,6 +580,10 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
private void evictEntry(K key) {
CacheEntry<K,V> o = map.remove(key);
+ postRemoveEntry(o);
+ }
+
+ private void postRemoveEntry(CacheEntry<K, V> o) {
if (o == null) return;
ramBytes.addAndGet(-(o.ramBytesUsed() + HASHTABLE_RAM_BYTES_PER_ENTRY));
stats.size.decrementAndGet();
@@ -594,14 +675,16 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
final K key;
final V value;
+ final long createTime;
final long ramBytesUsed; // cache
volatile long lastAccessed = 0;
long lastAccessedCopy = 0;
- public CacheEntry(K key, V value, long lastAccessed) {
+ public CacheEntry(K key, V value, long createTime, long lastAccessed) {
this.key = key;
this.value = value;
+ this.createTime = createTime;
this.lastAccessed = lastAccessed;
this.ramBytesUsed =
BASE_RAM_BYTES_USED +
@@ -672,7 +755,7 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
2 * (RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.primitiveSizes.get(long.class))
) +
// AtomicLong
- 2 * RamUsageEstimator.primitiveSizes.get(long.class) +
+ 3 * RamUsageEstimator.primitiveSizes.get(long.class) +
// AtomicInteger
RamUsageEstimator.primitiveSizes.get(int.class);
@@ -682,6 +765,7 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
private final LongAdder missCounter = new LongAdder();
private final AtomicInteger size = new AtomicInteger();
private AtomicLong evictionCounter = new AtomicLong();
+ private AtomicLong evictionIdleCounter = new AtomicLong();
public long getCumulativeLookups() {
return (accessCounter.longValue() - putCounter.longValue() - nonLivePutCounter.longValue()) + missCounter.longValue();
@@ -699,6 +783,10 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
return evictionCounter.get();
}
+ public long getCumulativeIdleEvictions() {
+ return evictionIdleCounter.get();
+ }
+
public int getCurrentSize() {
return size.get();
}
@@ -742,15 +830,18 @@ public class ConcurrentLRUCache<K,V> implements Cache<K,V>, Accountable {
@Override
public void run() {
while (true) {
+ ConcurrentLRUCache c = cache.get();
+ if(c == null) break;
synchronized (this) {
if (stop) break;
+ long waitTimeMs = c.maxIdleTimeNs != Long.MAX_VALUE ? TimeUnit.MILLISECONDS.convert(c.maxIdleTimeNs, TimeUnit.NANOSECONDS) : 0L;
try {
- this.wait();
+ this.wait(waitTimeMs);
} catch (InterruptedException e) {}
}
if (stop) break;
- ConcurrentLRUCache c = cache.get();
- if(c == null) break;
+ c = cache.get();
+ if (c == null) break;
c.markAndSweep();
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/TestFastLRUCache.java b/solr/core/src/test/org/apache/solr/search/TestFastLRUCache.java
index 0fb17651618..5844dac1466 100644
--- a/solr/core/src/test/org/apache/solr/search/TestFastLRUCache.java
+++ b/solr/core/src/test/org/apache/solr/search/TestFastLRUCache.java
@@ -23,6 +23,7 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCase;
+import org.apache.solr.common.util.TimeSource;
import org.apache.solr.metrics.MetricsMap;
import org.apache.solr.metrics.SolrMetricManager;
import org.apache.solr.util.ConcurrentLRUCache;
@@ -32,6 +33,8 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -280,7 +283,7 @@ public class TestFastLRUCache extends SolrTestCase {
int upperWaterMark = (int)(lowerWaterMark * 1.1);
Random r = random();
- ConcurrentLRUCache cache = new ConcurrentLRUCache(upperWaterMark, lowerWaterMark, (upperWaterMark+lowerWaterMark)/2, upperWaterMark, false, false, null);
+ ConcurrentLRUCache cache = new ConcurrentLRUCache(upperWaterMark, lowerWaterMark, (upperWaterMark+lowerWaterMark)/2, upperWaterMark, false, false, null, -1);
boolean getSize=false;
int minSize=0,maxSize=0;
for (int i=0; i<iter; i++) {
@@ -397,6 +400,41 @@ public class TestFastLRUCache extends SolrTestCase {
assertEquals(10, cache.size());
}
+ public void testMaxIdleTime() throws Exception {
+ int IDLE_TIME_SEC = 600;
+ long IDLE_TIME_NS = TimeUnit.NANOSECONDS.convert(IDLE_TIME_SEC, TimeUnit.SECONDS);
+ CountDownLatch sweepFinished = new CountDownLatch(1);
+ ConcurrentLRUCache<String, Accountable> cache = new ConcurrentLRUCache<>(6, 5, 5, 6, false, false, null, IDLE_TIME_SEC) {
+ @Override
+ public void markAndSweep() {
+ super.markAndSweep();
+ sweepFinished.countDown();
+ }
+ };
+ long currentTime = TimeSource.NANO_TIME.getEpochTimeNs();
+ for (int i = 0; i < 4; i++) {
+ cache.putCacheEntry(new ConcurrentLRUCache.CacheEntry<>("" + i, new Accountable() {
+ @Override
+ public long ramBytesUsed() {
+ return 1024 * 1024;
+ }
+ }, currentTime, 0));
+ }
+ // no evictions yet
+ assertEquals(4, cache.size());
+ assertEquals("markAndSweep spurious run", 1, sweepFinished.getCount());
+ cache.putCacheEntry(new ConcurrentLRUCache.CacheEntry<>("4", new Accountable() {
+ @Override
+ public long ramBytesUsed() {
+ return 0;
+ }
+ }, currentTime - IDLE_TIME_NS * 2, 0));
+ boolean await = sweepFinished.await(10, TimeUnit.SECONDS);
+ assertTrue("did not evict entries in time", await);
+ assertEquals(4, cache.size());
+ assertNull(cache.get("4"));
+ }
+
/***
public void testPerf() {
doPerfTest(1000000, 100000, 200000); // big cache, warmup
diff --git a/solr/core/src/test/org/apache/solr/search/TestLFUCache.java b/solr/core/src/test/org/apache/solr/search/TestLFUCache.java
index beac366cd4c..05e7557a2cb 100644
--- a/solr/core/src/test/org/apache/solr/search/TestLFUCache.java
+++ b/solr/core/src/test/org/apache/solr/search/TestLFUCache.java
@@ -22,8 +22,10 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.lucene.index.Term;
@@ -33,6 +35,7 @@ import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.TimeSource;
import org.apache.solr.metrics.SolrMetricManager;
import org.apache.solr.util.ConcurrentLFUCache;
import org.apache.solr.util.DefaultSolrThreadFactory;
@@ -494,6 +497,35 @@ public class TestLFUCache extends SolrTestCaseJ4 {
assertEquals(10, cache.size());
}
+ @Test
+ public void testMaxIdleTimeEviction() throws Exception {
+ int IDLE_TIME_SEC = 5;
+ long IDLE_TIME_NS = TimeUnit.NANOSECONDS.convert(IDLE_TIME_SEC, TimeUnit.SECONDS);
+ CountDownLatch sweepFinished = new CountDownLatch(1);
+ final AtomicLong numSweepsStarted = new AtomicLong(0);
+ ConcurrentLFUCache<String, String> cache = new ConcurrentLFUCache<>(6, 5, 5, 6, false, false, null, false, IDLE_TIME_SEC) {
+ @Override
+ public void markAndSweep() {
+ numSweepsStarted.incrementAndGet();
+ super.markAndSweep();
+ sweepFinished.countDown();
+ }
+ };
+ for (int i = 0; i < 4; i++) {
+ cache.put("" + i, "foo " + i);
+ }
+ // no evictions yet
+ assertEquals(4, cache.size());
+ assertEquals("markAndSweep spurious run", 0, numSweepsStarted.get());
+ long currentTime = TimeSource.NANO_TIME.getEpochTimeNs();
+ cache.putCacheEntry(new ConcurrentLFUCache.CacheEntry<>("4", "foo5",
+ currentTime - IDLE_TIME_NS * 2));
+ boolean await = sweepFinished.await(10, TimeUnit.SECONDS);
+ assertTrue("did not evict entries in time", await);
+ assertEquals(4, cache.size());
+ assertNull(cache.get("4"));
+ }
+
// From the original LRU cache tests, they're commented out there too because they take a while.
// void doPerfTest(int iter, int cacheSize, int maxKey) {
// long start = System.currentTimeMillis();
diff --git a/solr/core/src/test/org/apache/solr/search/TestLRUCache.java b/solr/core/src/test/org/apache/solr/search/TestLRUCache.java
index f9cd0dba842..f5b15a002cf 100644
--- a/solr/core/src/test/org/apache/solr/search/TestLRUCache.java
+++ b/solr/core/src/test/org/apache/solr/search/TestLRUCache.java
@@ -19,12 +19,15 @@ package org.apache.solr.search;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
import org.apache.lucene.util.Accountable;
import org.apache.solr.SolrTestCase;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.TestUtil;
+import org.apache.solr.common.util.TimeSource;
import org.apache.solr.metrics.SolrMetricManager;
+import org.junit.Test;
/**
* Test for <code>org.apache.solr.search.LRUCache</code>
@@ -145,7 +148,7 @@ public class TestLRUCache extends SolrTestCase {
}
});
assertEquals(1, accountableLRUCache.size());
- assertEquals(baseSize + 512 * 1024 + RamUsageEstimator.sizeOfObject("1") + RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY, accountableLRUCache.ramBytesUsed());
+ assertEquals(baseSize + 512 * 1024 + RamUsageEstimator.sizeOfObject("1") + RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + LRUCache.CacheValue.BASE_RAM_BYTES_USED, accountableLRUCache.ramBytesUsed());
accountableLRUCache.put("20", new Accountable() {
@Override
public long ramBytesUsed() {
@@ -153,7 +156,7 @@ public class TestLRUCache extends SolrTestCase {
}
});
assertEquals(1, accountableLRUCache.size());
- assertEquals(baseSize + 512 * 1024 + RamUsageEstimator.sizeOfObject("20") + RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY, accountableLRUCache.ramBytesUsed());
+ assertEquals(baseSize + 512 * 1024 + RamUsageEstimator.sizeOfObject("20") + RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + LRUCache.CacheValue.BASE_RAM_BYTES_USED, accountableLRUCache.ramBytesUsed());
Map<String,Object> nl = accountableLRUCache.getMetricsMap().getValue();
assertEquals(1L, nl.get("evictions"));
assertEquals(1L, nl.get("evictionsRamUsage"));
@@ -167,7 +170,8 @@ public class TestLRUCache extends SolrTestCase {
assertEquals(1L, nl.get("evictions"));
assertEquals(1L, nl.get("evictionsRamUsage"));
assertEquals(2L, accountableLRUCache.size());
- assertEquals(baseSize + 513 * 1024 + RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY * 2 +
+ assertEquals(baseSize + 513 * 1024 +
+ (RamUsageEstimator.LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + LRUCache.CacheValue.BASE_RAM_BYTES_USED) * 2 +
RamUsageEstimator.sizeOfObject("20") + RamUsageEstimator.sizeOfObject("300"), accountableLRUCache.ramBytesUsed());
accountableLRUCache.clear();
@@ -255,4 +259,39 @@ public class TestLRUCache extends SolrTestCase {
}
assertEquals(10, cache.size());
}
+
+ @Test
+ public void testMaxIdleTime() throws Exception {
+ int IDLE_TIME_SEC = 600;
+ long IDLE_TIME_NS = TimeUnit.NANOSECONDS.convert(IDLE_TIME_SEC, TimeUnit.SECONDS);
+ LRUCache<String, Accountable> cache = new LRUCache<>();
+ cache.initializeMetrics(metricManager, registry, "foo", scope);
+ Map<String, String> params = new HashMap<>();
+ params.put("size", "6");
+ params.put("maxIdleTime", "" + IDLE_TIME_SEC);
+ CacheRegenerator cr = new NoOpRegenerator();
+ Object o = cache.init(params, null, cr);
+ cache.setSyntheticEntries(true);
+ for (int i = 0; i < 4; i++) {
+ cache.put("" + i, new Accountable() {
+ @Override
+ public long ramBytesUsed() {
+ return 1024 * 1024;
+ }
+ });
+ }
+ // no evictions yet
+ assertEquals(4, cache.size());
+ long currentTime = TimeSource.NANO_TIME.getEpochTimeNs();
+ cache.putCacheValue("4", new LRUCache.CacheValue<>(new Accountable() {
+ @Override
+ public long ramBytesUsed() {
+ return 0;
+ }
+ }, currentTime - IDLE_TIME_NS * 2));
+ assertEquals(4, cache.size());
+ assertNull(cache.get("4"));
+ Map<String, Object> stats = cache.getMetricsMap().getValue();
+ assertEquals(1, ((Number)stats.get("evictionsIdleTime")).intValue());
+ }
}
diff --git a/solr/solr-ref-guide/src/query-settings-in-solrconfig.adoc b/solr/solr-ref-guide/src/query-settings-in-solrconfig.adoc
index 20e83cc54ce..3729e53d18d 100644
--- a/solr/solr-ref-guide/src/query-settings-in-solrconfig.adoc
+++ b/solr/solr-ref-guide/src/query-settings-in-solrconfig.adoc
@@ -29,7 +29,7 @@ These settings are all configured in child elements of the `<query>` element in
== Caches
-Solr caches are associated with a specific instance of an Index Searcher, a specific view of an index that doesn't change during the lifetime of that searcher. As long as that Index Searcher is being used, any items in its cache will be valid and available for reuse. Caching in Solr differs from caching in many other applications in that cached Solr objects do not expire after a time interval; instead, they remain valid for the lifetime of the Index Searcher.
+Solr caches are associated with a specific instance of an Index Searcher, a specific view of an index that doesn't change during the lifetime of that searcher. As long as that Index Searcher is being used, any items in its cache will be valid and available for reuse. By default cached Solr objects do not expire after a time interval; instead, they remain valid for the lifetime of the Index Searcher. Idle time-based expiration can be enabled by using `maxIdleTime` option.
When a new searcher is opened, the current searcher continues servicing requests while the new one auto-warms its cache. The new searcher uses the current searcher's cache to pre-populate its own. When the new searcher is ready, it is registered as the current searcher and begins handling all new search requests. The old searcher will be closed once it has finished servicing all its requests.
@@ -47,7 +47,9 @@ The Statistics page in the Solr Admin UI will display information about the perf
Each cache has settings to define its initial size (`initialSize`), maximum size (`size`) and number of items to use for during warming (`autowarmCount`). The LRU and FastLRU cache implementations can take a percentage instead of an absolute value for `autowarmCount`.
-FastLRUCache and LFUCache support `showItems` attribute. This is the number of cache items to display in the stats page for the cache. It is for debugging.
+Each cache implementation also supports a `maxIdleTime` attribute that controls the automatic eviction of entries that haven't been used for a while. This attribute is expressed in seconds, with the default value of `0` meaning no entries are automatically evicted due to exceeded idle time. Smaller values of this attribute will cause older entries to be evicted quickly, which will reduce cache memory usage but may instead cause thrashing due to a repeating eviction-lookup-miss-insertion cycle of the same entries. Larger values will cause entries to stay around longer, waiting to be reused, at the cost of increased memory usage. Reasonable values, depending on the query volume and patterns, may lie somewhere between 60-3600. Please note that this condition is evaluated synchronously and before other eviction conditions on every entry insertion.
+
+`FastLRUCache` and `LFUCache` support `showItems` attribute. This is the number of cache items to display in the stats page for the cache. It is for debugging.
Details of each cache are described below.