You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimpleLruCache.java 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright (C) 2019, Marc Strapetz <marc.strapetz@syntevo.com>
  3. * Copyright (C) 2019, Matthias Sohn <matthias.sohn@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.util;
  45. import java.text.MessageFormat;
  46. import java.util.ArrayList;
  47. import java.util.Collections;
  48. import java.util.Comparator;
  49. import java.util.List;
  50. import java.util.Map;
  51. import java.util.concurrent.ConcurrentHashMap;
  52. import java.util.concurrent.locks.Lock;
  53. import java.util.concurrent.locks.ReentrantLock;
  54. import org.eclipse.jgit.annotations.NonNull;
  55. import org.eclipse.jgit.internal.JGitText;
  56. /**
  57. * Simple limited size cache based on ConcurrentHashMap purging entries in LRU
  58. * order when reaching size limit
  59. *
  60. * @param <K>
  61. * the type of keys maintained by this cache
  62. * @param <V>
  63. * the type of mapped values
  64. *
  65. * @since 5.1.9
  66. */
  67. public class SimpleLruCache<K, V> {
  68. private static class Entry<K, V> {
  69. private final K key;
  70. private final V value;
  71. // pseudo clock timestamp of the last access to this entry
  72. private volatile long lastAccessed;
  73. private long lastAccessedSorting;
  74. Entry(K key, V value, long lastAccessed) {
  75. this.key = key;
  76. this.value = value;
  77. this.lastAccessed = lastAccessed;
  78. }
  79. void copyAccessTime() {
  80. lastAccessedSorting = lastAccessed;
  81. }
  82. @SuppressWarnings("nls")
  83. @Override
  84. public String toString() {
  85. return "Entry [lastAccessed=" + lastAccessed + ", key=" + key
  86. + ", value=" + value + "]";
  87. }
  88. }
  89. private Lock lock = new ReentrantLock();
  90. private Map<K, Entry<K,V>> map = new ConcurrentHashMap<>();
  91. private volatile int maximumSize;
  92. private int purgeSize;
  93. // pseudo clock to implement LRU order of access to entries
  94. private volatile long time = 0L;
  95. private static void checkPurgeFactor(float purgeFactor) {
  96. if (purgeFactor <= 0 || purgeFactor >= 1) {
  97. throw new IllegalArgumentException(
  98. MessageFormat.format(JGitText.get().invalidPurgeFactor,
  99. Float.valueOf(purgeFactor)));
  100. }
  101. }
  102. private static int purgeSize(int maxSize, float purgeFactor) {
  103. return (int) ((1 - purgeFactor) * maxSize);
  104. }
  105. /**
  106. * Create a new cache
  107. *
  108. * @param maxSize
  109. * maximum size of the cache, to reduce need for synchronization
  110. * this is not a hard limit. The real size of the cache could be
  111. * slightly above this maximum if multiple threads put new values
  112. * concurrently
  113. * @param purgeFactor
  114. * when the size of the map reaches maxSize the oldest entries
  115. * will be purged to free up some space for new entries,
  116. * {@code purgeFactor} is the fraction of {@code maxSize} to
  117. * purge when this happens
  118. */
  119. public SimpleLruCache(int maxSize, float purgeFactor) {
  120. checkPurgeFactor(purgeFactor);
  121. this.maximumSize = maxSize;
  122. this.purgeSize = purgeSize(maxSize, purgeFactor);
  123. }
  124. /**
  125. * Returns the value to which the specified key is mapped, or {@code null}
  126. * if this map contains no mapping for the key.
  127. *
  128. * <p>
  129. * More formally, if this cache contains a mapping from a key {@code k} to a
  130. * value {@code v} such that {@code key.equals(k)}, then this method returns
  131. * {@code v}; otherwise it returns {@code null}. (There can be at most one
  132. * such mapping.)
  133. *
  134. * @param key
  135. * the key
  136. *
  137. * @throws NullPointerException
  138. * if the specified key is null
  139. *
  140. * @return value mapped for this key, or {@code null} if no value is mapped
  141. */
  142. public V get(Object key) {
  143. Entry<K, V> entry = map.get(key);
  144. if (entry != null) {
  145. entry.lastAccessed = ++time;
  146. return entry.value;
  147. }
  148. return null;
  149. }
  150. /**
  151. * Maps the specified key to the specified value in this cache. Neither the
  152. * key nor the value can be null.
  153. *
  154. * <p>
  155. * The value can be retrieved by calling the {@code get} method with a key
  156. * that is equal to the original key.
  157. *
  158. * @param key
  159. * key with which the specified value is to be associated
  160. * @param value
  161. * value to be associated with the specified key
  162. * @return the previous value associated with {@code key}, or {@code null}
  163. * if there was no mapping for {@code key}
  164. * @throws NullPointerException
  165. * if the specified key or value is null
  166. */
  167. public V put(@NonNull K key, @NonNull V value) {
  168. map.put(key, new Entry<>(key, value, ++time));
  169. if (map.size() > maximumSize) {
  170. purge();
  171. }
  172. return value;
  173. }
  174. /**
  175. * Returns the current size of this cache
  176. *
  177. * @return the number of key-value mappings in this cache
  178. */
  179. public int size() {
  180. return map.size();
  181. }
  182. /**
  183. * Reconfigures the cache. If {@code maxSize} is reduced some entries will
  184. * be purged.
  185. *
  186. * @param maxSize
  187. * maximum size of the cache
  188. *
  189. * @param purgeFactor
  190. * when the size of the map reaches maxSize the oldest entries
  191. * will be purged to free up some space for new entries,
  192. * {@code purgeFactor} is the fraction of {@code maxSize} to
  193. * purge when this happens
  194. */
  195. public void configure(int maxSize, float purgeFactor) {
  196. lock.lock();
  197. try {
  198. checkPurgeFactor(purgeFactor);
  199. this.maximumSize = maxSize;
  200. this.purgeSize = purgeSize(maxSize, purgeFactor);
  201. if (map.size() >= maximumSize) {
  202. purge();
  203. }
  204. } finally {
  205. lock.unlock();
  206. }
  207. }
  208. private void purge() {
  209. // don't try to compete if another thread already has the lock
  210. if (lock.tryLock()) {
  211. try {
  212. List<Entry> entriesToPurge = new ArrayList<>(map.values());
  213. // copy access times to avoid other threads interfere with
  214. // sorting
  215. for (Entry e : entriesToPurge) {
  216. e.copyAccessTime();
  217. }
  218. Collections.sort(entriesToPurge,
  219. Comparator.comparingLong(o -> -o.lastAccessedSorting));
  220. for (int index = purgeSize; index < entriesToPurge
  221. .size(); index++) {
  222. map.remove(entriesToPurge.get(index).key);
  223. }
  224. } finally {
  225. lock.unlock();
  226. }
  227. }
  228. }
  229. }