You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2017/12/11 01:28:42 UTC

groovy git commit: Implement another LRU cache

Repository: groovy
Updated Branches:
  refs/heads/master a6f2133fc -> 4d729e45a


Implement another LRU cache


Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/4d729e45
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/4d729e45
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/4d729e45

Branch: refs/heads/master
Commit: 4d729e45a13a499cf349d9e465d6a5e4dfb1c54d
Parents: a6f2133
Author: sunlan <su...@apache.org>
Authored: Mon Dec 11 09:28:36 2017 +0800
Committer: sunlan <su...@apache.org>
Committed: Mon Dec 11 09:28:36 2017 +0800

----------------------------------------------------------------------
 .../groovy/runtime/memoize/CommonCache.java       | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/groovy/blob/4d729e45/src/main/org/codehaus/groovy/runtime/memoize/CommonCache.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/memoize/CommonCache.java b/src/main/org/codehaus/groovy/runtime/memoize/CommonCache.java
index ff521cd..024dc915e 100644
--- a/src/main/org/codehaus/groovy/runtime/memoize/CommonCache.java
+++ b/src/main/org/codehaus/groovy/runtime/memoize/CommonCache.java
@@ -22,6 +22,7 @@ import java.lang.ref.SoftReference;
 import java.lang.ref.WeakReference;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -43,10 +44,27 @@ public class CommonCache<K, V> implements EvictableCache<K, V> {
     private final ReentrantReadWriteLock.ReadLock readLock = rwl.readLock();
     private final ReentrantReadWriteLock.WriteLock writeLock = rwl.writeLock();
 
+    /**
+     * A cache with unlimited size
+     */
     public CommonCache() {
         this(new HashMap<K, V>());
     }
 
+    /**
+     * Another LRU cache, which is slower than {@link LRUCache} but will not put same value multi-times concurrently
+     * @param initialCapacity
+     * @param maxSize
+     */
+    public CommonCache(final int initialCapacity, final int maxSize) {
+        this(new LinkedHashMap<K, V>(initialCapacity, 0.75f, true) {
+            @Override
+            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
+                return size() > maxSize;
+            }
+        });
+    }
+
     public CommonCache(Map<K, V> map) {
         this.map = map;
     }