Debian Codegraph @

net/sf/saxon/expr/sort/LRUCache.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.sort;
9
10 import java.util.Collections;
11 import java.util.LinkedHashMap;
12 import java.util.Map;
13
14 /**
15 * An LRU cache, based on <code>LinkedHashMap</code>.
16 * Synthesized and simplified from various published examples of the genre.
17 * The methods are not synchronized.
18 */
19 public class LRUCache<K, V> {
20
21 private Map<K, V> map;
22
23 /**
24 * Creates a new LRU cache.
25 *
26 * @param cacheSize the maximum number of entries that will be kept in this cache.
27 */
28 public LRUCache(final int cacheSize) {
29 this(cacheSize, false);
30 }
31
32 /**
33 * Creates a new LRU cache, with the option of making it thread-safe
34 *
35 * @param cacheSize the maximum number of entries that will be kept in this cache.
36 * @param concurrent set to true if concurrent access is required, so that access will
37 * be synchronized
38 */
39 public LRUCache(final int cacheSize, boolean concurrent) {
40 map = new LinkedHashMap<K, V>(cacheSize, 0.75f, true) {
41 protected boolean removeEldestEntry(Map.Entry eldest) {
42 return cacheSize < super.size();
43 }
44 };
45 if (concurrent) {
46 map = Collections.synchronizedMap(map);
47 }
48 }
49
50 /**
51 * Retrieves an entry from the cache.<br>
52 * The retrieved entry becomes the most recently used entry.
53 *
54 * @param key the key whose associated value is to be returned.
55 * @return the value associated to this key, or null if no value with this key exists in the cache.
56 */
57 public V get(K key) {
58 return map.get(key);
59 }
60
61 /**
62 * Adds an entry to this cache.
63 * If the cache is full, the LRU (least recently used) entry is dropped.
64 *
65 * @param key the key with which the specified value is to be associated.
66 * @param value a value to be associated with the specified key.
67 */
68 public void put(K key, V value) {
69 map.put(key, value);
70 }
71
72 /**
73 * Clear the cache
74 */
75 public void clear() {
76 map.clear();
77 }
78
79 /**
80 * Get the number of entries in the cache
81 *
82 * @return the number of entries
83 */
84
85 public int size() {
86 return map.size();
87 }
88
89
90 }