|
26 | 26 | import org.slf4j.LoggerFactory;
|
27 | 27 |
|
28 | 28 | import java.util.Collections;
|
| 29 | +import java.util.LinkedHashMap; |
29 | 30 | import java.util.Map;
|
30 |
| -import java.util.concurrent.ConcurrentHashMap; |
31 | 31 | import java.util.concurrent.TimeUnit;
|
32 | 32 | import java.util.concurrent.atomic.AtomicBoolean;
|
33 | 33 |
|
34 | 34 | /**
|
35 |
| - * In-memory {@link StateBackingStore} implementation. |
| 35 | + * An in-memory {@link StateBackingStore} implementation that uses an LRU cache based on HashMap. |
36 | 36 | */
|
37 | 37 | public class InMemoryFileObjectStateBackingStore implements FileObjectStateBackingStore {
|
38 | 38 |
|
39 | 39 | private static final Logger LOG = LoggerFactory.getLogger(InMemoryFileObjectStateBackingStore.class);
|
40 | 40 |
|
41 |
| - private final ConcurrentHashMap<String, FileObject> objects = new ConcurrentHashMap<>(); |
| 41 | + private static final int DEFAULT_MAX_SIZE_CAPACITY = 10_000; |
| 42 | + |
| 43 | + private final Map<String, FileObject> objects; |
42 | 44 |
|
43 | 45 | private StateBackingStore.UpdateListener<FileObject> listener;
|
44 | 46 |
|
45 | 47 | private final AtomicBoolean started = new AtomicBoolean(false);
|
46 | 48 |
|
47 |
| - public InMemoryFileObjectStateBackingStore() { } |
| 49 | + public InMemoryFileObjectStateBackingStore() { |
| 50 | + this.objects = Collections.synchronizedMap(createLRUCache(DEFAULT_MAX_SIZE_CAPACITY)); |
| 51 | + } |
48 | 52 |
|
49 | 53 | @VisibleForTesting
|
50 | 54 | public InMemoryFileObjectStateBackingStore(final Map<String, FileObject> objects) {
|
| 55 | + this(); |
51 | 56 | this.objects.putAll(objects);
|
52 | 57 | }
|
53 | 58 |
|
@@ -150,4 +155,13 @@ public void setUpdateListener(final UpdateListener<FileObject> listener) {
|
150 | 155 | public UpdateListener<FileObject> getListener() {
|
151 | 156 | return listener;
|
152 | 157 | }
|
| 158 | + |
| 159 | + private static <K, V> Map<K, V> createLRUCache(final int maxCacheSize) { |
| 160 | + return new LinkedHashMap<>(maxCacheSize + 1, 1.01f, true) { |
| 161 | + @Override |
| 162 | + protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) { |
| 163 | + return size() > maxCacheSize; |
| 164 | + } |
| 165 | + }; |
| 166 | + } |
153 | 167 | }
|
0 commit comments