Debian Codegraph @

src/org/tukaani/xz/BasicArrayCache.java

raw symbols SCIP
1 // SPDX-License-Identifier: 0BSD
2 // SPDX-FileCopyrightText: The XZ for Java authors and contributors
3 // SPDX-FileContributor: Lasse Collin <[email protected]>
4
5 package org.tukaani.xz;
6
7 import java.lang.ref.Reference;
8 import java.lang.ref.SoftReference;
9 import java.util.Arrays;
10 import java.util.LinkedHashMap;
11 import java.util.Map;
12
13 /**
14 * A basic {@link ArrayCache} implementation.
15 * <p>
16 * This caches exact array sizes, that is, {@code getByteArray} will return
17 * an array whose size is exactly the requested size. A limited number
18 * of different array sizes are cached at the same time; least recently used
19 * sizes will be dropped from the cache if needed (can happen if several
20 * different (de)compression options are used with the same cache).
21 * <p>
22 * The current implementation uses
23 * {@link java.util.LinkedHashMap LinkedHashMap} to map different array sizes
24 * to separate array-based data structures which hold
25 * {@link java.lang.ref.SoftReference SoftReferences} to the cached arrays.
26 * In the common case this should give good performance and fairly low
27 * memory usage overhead.
28 * <p>
29 * A statically allocated global {@code BasicArrayCache} instance is
30 * available via {@link #getInstance()} which is a good choice in most
31 * situations where caching is wanted.
32 *
33 * @since 1.7
34 */
35 public class BasicArrayCache extends ArrayCache {
36 /**
37 * Arrays smaller than this many elements will not be cached.
38 */
39 private static final int CACHEABLE_SIZE_MIN = 32 << 10;
40
41 /**
42 * Number of stacks i.e. how many different array sizes to cache.
43 */
44 private static final int STACKS_MAX = 32;
45
46 /**
47 * Number of arrays of the same type and size to keep in the cache.
48 * (ELEMENTS_PER_STACK - 1) is used as a bit mask so ELEMENTS_PER_STACK
49 * must be a power of two!
50 */
51 private static final int ELEMENTS_PER_STACK = 512;
52
53 /**
54 * A thread-safe stack-like data structure whose {@code push} method
55 * overwrites the oldest element in the stack if the stack is full.
56 */
57 private static class CyclicStack<T> {
58 /**
59 * Array that holds the elements in the cyclic stack.
60 */
61 @SuppressWarnings("unchecked")
62 private final T[] elements = (T[])new Object[ELEMENTS_PER_STACK];
63
64 /**
65 * Read-write position in the {@code refs} array.
66 * The most recently added element is in {@code refs[pos]}.
67 * If it is {@code null}, then the stack is empty and all
68 * elements in {@code refs} are {@code null}.
69 * <p>
70 * Note that {@code pop()} always modifies {@code pos}, even if
71 * the stack is empty. This means that when the first element is
72 * added by {@code push(T)}, it can get added in any position in
73 * {@code refs} and the stack will start growing from there.
74 */
75 private int pos = 0;
76
77 /**
78 * Gets the most recently added element from the stack.
79 * If the stack is empty, {@code null} is returned.
80 */
81 public synchronized T pop() {
82 T e = elements[pos];
83 elements[pos] = null;
84 pos = (pos - 1) & (ELEMENTS_PER_STACK - 1);
85 return e;
86 }
87
88 /**
89 * Adds a new element to the stack. If the stack is full, the oldest
90 * element is overwritten.
91 */
92 public synchronized void push(T e) {
93 pos = (pos + 1) & (ELEMENTS_PER_STACK - 1);
94 elements[pos] = e;
95 }
96 }
97
98 /**
99 * Maps Integer (array size) to stacks of references to arrays. At most
100 * STACKS_MAX number of stacks are kept in the map (LRU cache).
101 */
102 private static class CacheMap<T>
103 extends LinkedHashMap<Integer, CyclicStack<Reference<T>>> {
104 /**
105 * This class won't be serialized but this is needed
106 * to silence a compiler warning.
107 */
108 private static final long serialVersionUID = 1L;
109
110 /**
111 * Creates a new CacheMap.
112 */
113 public CacheMap() {
114 // The map may momentarily have at most STACKS_MAX + 1 entries
115 // when put(K,V) has inserted a new entry but hasn't called
116 // removeEldestEntry yet. Using 2 * STACKS_MAX as the initial
117 // (and the final) capacity should give good performance. 0.75 is
118 // the default load factor and in this case it guarantees that
119 // the map will never need to be rehashed because
120 // (STACKS_MAX + 1) / 0.75 < 2 * STACKS_MAX.
121 //
122 // That last argument is true to get LRU cache behavior together
123 // with the overridden removeEldestEntry method.
124 super(2 * STACKS_MAX, 0.75f, true);
125 }
126
127 /**
128 * Returns true if the map is full and the least recently used stack
129 * should be removed.
130 */
131 @Override
132 protected boolean removeEldestEntry(
133 Map.Entry<Integer, CyclicStack<Reference<T>>> eldest) {
134 return size() > STACKS_MAX;
135 }
136 }
137
138 /**
139 * Helper class for the singleton instance.
140 * This is allocated only if {@code getInstance()} is called.
141 */
142 private static final class LazyHolder {
143 static final BasicArrayCache INSTANCE = new BasicArrayCache();
144 }
145
146 /**
147 * Returns a statically-allocated {@code BasicArrayCache} instance.
148 * This is often a good choice when a cache is needed.
149 */
150 public static BasicArrayCache getInstance() {
151 return LazyHolder.INSTANCE;
152 }
153
154 /**
155 * Stacks for cached byte arrays.
156 */
157 private final CacheMap<byte[]> byteArrayCache = new CacheMap<byte[]>();
158
159 /**
160 * Stacks for cached int arrays.
161 */
162 private final CacheMap<int[]> intArrayCache = new CacheMap<int[]>();
163
164 /**
165 * Gets {@code T[size]} from the given {@code cache}.
166 * If no such array is found, {@code null} is returned.
167 */
168 private static <T> T getArray(CacheMap<T> cache, int size) {
169 // putArray doesn't add small arrays to the cache and so it's
170 // pointless to look for small arrays here.
171 if (size < CACHEABLE_SIZE_MIN)
172 return null;
173
174 // Try to find a stack that holds arrays of T[size].
175 CyclicStack<Reference<T>> stack;
176 synchronized(cache) {
177 stack = cache.get(size);
178 }
179
180 if (stack == null)
181 return null;
182
183 // Try to find a non-cleared Reference from the stack.
184 T array;
185 do {
186 Reference<T> r = stack.pop();
187 if (r == null)
188 return null;
189
190 array = r.get();
191 } while (array == null);
192
193 return array;
194 }
195
196 /**
197 * Puts the {@code array} of {@code size} elements long into
198 * the {@code cache}.
199 */
200 private static <T> void putArray(CacheMap<T> cache, T array, int size) {
201 // Small arrays aren't cached.
202 if (size < CACHEABLE_SIZE_MIN)
203 return;
204
205 CyclicStack<Reference<T>> stack;
206
207 synchronized(cache) {
208 // Get a stack that holds arrays of T[size]. If no such stack
209 // exists, allocate a new one. If the cache already had STACKS_MAX
210 // number of stacks, the least recently used stack is removed by
211 // cache.put (it calls removeEldestEntry).
212 stack = cache.get(size);
213 if (stack == null) {
214 stack = new CyclicStack<Reference<T>>();
215 cache.put(size, stack);
216 }
217 }
218
219 stack.push(new SoftReference<T>(array));
220 }
221
222 /**
223 * Allocates a new byte array, hopefully reusing an existing
224 * array from the cache.
225 *
226 * @param size size of the array to allocate
227 *
228 * @param fillWithZeros
229 * if true, all the elements of the returned
230 * array will be zero; if false, the contents
231 * of the returned array is undefined
232 */
233 @Override
234 public byte[] getByteArray(int size, boolean fillWithZeros) {
235 byte[] array = getArray(byteArrayCache, size);
236
237 if (array == null)
238 array = new byte[size];
239 else if (fillWithZeros)
240 Arrays.fill(array, (byte)0x00);
241
242 return array;
243 }
244
245 /**
246 * Puts the given byte array to the cache. The caller must no longer
247 * use the array.
248 * <p>
249 * Small arrays aren't cached and will be ignored by this method.
250 */
251 @Override
252 public void putArray(byte[] array) {
253 putArray(byteArrayCache, array, array.length);
254 }
255
256 /**
257 * This is like getByteArray but for int arrays.
258 */
259 @Override
260 public int[] getIntArray(int size, boolean fillWithZeros) {
261 int[] array = getArray(intArrayCache, size);
262
263 if (array == null)
264 array = new int[size];
265 else if (fillWithZeros)
266 Arrays.fill(array, 0);
267
268 return array;
269 }
270
271 /**
272 * Puts the given int array to the cache. The caller must no longer
273 * use the array.
274 * <p>
275 * Small arrays aren't cached and will be ignored by this method.
276 */
277 @Override
278 public void putArray(int[] array) {
279 putArray(intArrayCache, array, array.length);
280 }
281 }