Debian Codegraph @

src/main/org/h2/store/fs/niomem/FileNioMemData.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.store.fs.niomem;
7
8 import java.nio.ByteBuffer;
9 import java.nio.channels.NonWritableChannelException;
10 import java.util.LinkedHashMap;
11 import java.util.Map;
12 import java.util.concurrent.atomic.AtomicReference;
13 import java.util.concurrent.locks.ReentrantReadWriteLock;
14 import org.h2.compress.CompressLZF;
15 import org.h2.util.MathUtils;
16
17 /**
18 * This class contains the data of an in-memory random access file.
19 * Data compression using the LZF algorithm is supported as well.
20 */
21 class FileNioMemData {
22
23 private static final int CACHE_MIN_SIZE = 8;
24 private static final int BLOCK_SIZE_SHIFT = 16;
25
26 private static final int BLOCK_SIZE = 1 << BLOCK_SIZE_SHIFT;
27 private static final int BLOCK_SIZE_MASK = BLOCK_SIZE - 1;
28 private static final ByteBuffer COMPRESSED_EMPTY_BLOCK;
29
30 private static final ThreadLocal<CompressLZF> LZF_THREAD_LOCAL = ThreadLocal.withInitial(CompressLZF::new);
31
32 /** the output buffer when compressing */
33 private static final ThreadLocal<byte[]> COMPRESS_OUT_BUF_THREAD_LOCAL = ThreadLocal
34 .withInitial(() -> new byte[BLOCK_SIZE * 2]);
35
36 /**
37 * The hash code of the name.
38 */
39 final int nameHashCode;
40
41 private final CompressLaterCache<CompressItem, CompressItem> compressLaterCache =
42 new CompressLaterCache<>(CACHE_MIN_SIZE);
43
44 private String name;
45 private final boolean compress;
46 private final float compressLaterCachePercent;
47 private volatile long length;
48 private volatile AtomicReference<ByteBuffer>[] buffers;
49 private long lastModified;
50 private boolean isReadOnly;
51 private boolean isLockedExclusive;
52 private int sharedLockCount;
53 private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
54
55 static {
56 final byte[] n = new byte[BLOCK_SIZE];
57 final byte[] output = new byte[BLOCK_SIZE * 2];
58 int len = new CompressLZF().compress(n, 0, BLOCK_SIZE, output, 0);
59 COMPRESSED_EMPTY_BLOCK = ByteBuffer.allocateDirect(len);
60 COMPRESSED_EMPTY_BLOCK.put(output, 0, len);
61 }
62
63 @SuppressWarnings("unchecked")
64 FileNioMemData(String name, boolean compress, float compressLaterCachePercent) {
65 this.name = name;
66 this.nameHashCode = name.hashCode();
67 this.compress = compress;
68 this.compressLaterCachePercent = compressLaterCachePercent;
69 buffers = new AtomicReference[0];
70 lastModified = System.currentTimeMillis();
71 }
72
73 /**
74 * Lock the file in exclusive mode if possible.
75 *
76 * @return if locking was successful
77 */
78 synchronized boolean lockExclusive() {
79 if (sharedLockCount > 0 || isLockedExclusive) {
80 return false;
81 }
82 isLockedExclusive = true;
83 return true;
84 }
85
86 /**
87 * Lock the file in shared mode if possible.
88 *
89 * @return if locking was successful
90 */
91 synchronized boolean lockShared() {
92 if (isLockedExclusive) {
93 return false;
94 }
95 sharedLockCount++;
96 return true;
97 }
98
99 /**
100 * Unlock the file.
101 */
102 synchronized void unlock() {
103 if (isLockedExclusive) {
104 isLockedExclusive = false;
105 } else {
106 sharedLockCount = Math.max(0, sharedLockCount - 1);
107 }
108 }
109
110 /**
111 * This small cache compresses the data if an element leaves the cache.
112 */
113 static class CompressLaterCache<K, V> extends LinkedHashMap<K, V> {
114
115 private static final long serialVersionUID = 1L;
116 private int size;
117
118 CompressLaterCache(int size) {
119 super(size, (float) 0.75, true);
120 this.size = size;
121 }
122
123 @Override
124 public synchronized V put(K key, V value) {
125 return super.put(key, value);
126 }
127
128 @Override
129 protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
130 if (size() < size) {
131 return false;
132 }
133 CompressItem c = (CompressItem) eldest.getKey();
134 c.data.compressPage(c.page);
135 return true;
136 }
137
138 public void setCacheSize(int size) {
139 this.size = size;
140 }
141 }
142
143 /**
144 * Represents a compressed item.
145 */
146 static class CompressItem {
147
148 /**
149 * The file data.
150 */
151 public final FileNioMemData data;
152
153 /**
154 * The page to compress.
155 */
156 public final int page;
157
158 public CompressItem(FileNioMemData data, int page) {
159 this.data = data;
160 this.page = page;
161 }
162
163 @Override
164 public int hashCode() {
165 return page ^ data.nameHashCode;
166 }
167
168 @Override
169 public boolean equals(Object o) {
170 if (o instanceof CompressItem) {
171 CompressItem c = (CompressItem) o;
172 return c.data == data && c.page == page;
173 }
174 return false;
175 }
176
177 }
178
179 private void addToCompressLaterCache(int page) {
180 CompressItem c = new CompressItem(this, page);
181 compressLaterCache.put(c, c);
182 }
183
184 private ByteBuffer expandPage(int page) {
185 final ByteBuffer d = buffers[page].get();
186 if (d.capacity() == BLOCK_SIZE) {
187 // already expanded, or not compressed
188 return d;
189 }
190 synchronized (d) {
191 if (d.capacity() == BLOCK_SIZE) {
192 return d;
193 }
194 ByteBuffer out = ByteBuffer.allocateDirect(BLOCK_SIZE);
195 if (d != COMPRESSED_EMPTY_BLOCK) {
196 d.position(0);
197 CompressLZF.expand(d, out);
198 }
199 buffers[page].compareAndSet(d, out);
200 return out;
201 }
202 }
203
204 /**
205 * Compress the data in a byte array.
206 *
207 * @param page which page to compress
208 */
209 void compressPage(int page) {
210 final ByteBuffer d = buffers[page].get();
211 synchronized (d) {
212 if (d.capacity() != BLOCK_SIZE) {
213 // already compressed
214 return;
215 }
216 final byte[] compressOutputBuffer = COMPRESS_OUT_BUF_THREAD_LOCAL.get();
217 int len = LZF_THREAD_LOCAL.get().compress(d, 0, compressOutputBuffer, 0);
218 ByteBuffer out = ByteBuffer.allocateDirect(len);
219 out.put(compressOutputBuffer, 0, len);
220 buffers[page].compareAndSet(d, out);
221 }
222 }
223
224 /**
225 * Update the last modified time.
226 *
227 * @param openReadOnly if the file was opened in read-only mode
228 */
229 void touch(boolean openReadOnly) {
230 if (isReadOnly || openReadOnly) {
231 throw new NonWritableChannelException();
232 }
233 lastModified = System.currentTimeMillis();
234 }
235
236 /**
237 * Get the file length.
238 *
239 * @return the length
240 */
241 long length() {
242 return length;
243 }
244
245 /**
246 * Truncate the file.
247 *
248 * @param newLength the new length
249 */
250 void truncate(long newLength) {
251 rwLock.writeLock().lock();
252 try {
253 changeLength(newLength);
254 long end = MathUtils.roundUpLong(newLength, BLOCK_SIZE);
255 if (end != newLength) {
256 int lastPage = (int) (newLength >>> BLOCK_SIZE_SHIFT);
257 ByteBuffer d = expandPage(lastPage);
258 for (int i = (int) (newLength & BLOCK_SIZE_MASK); i < BLOCK_SIZE; i++) {
259 d.put(i, (byte) 0);
260 }
261 if (compress) {
262 addToCompressLaterCache(lastPage);
263 }
264 }
265 } finally {
266 rwLock.writeLock().unlock();
267 }
268 }
269
270 @SuppressWarnings("unchecked")
271 private void changeLength(long len) {
272 length = len;
273 len = MathUtils.roundUpLong(len, BLOCK_SIZE);
274 int blocks = (int) (len >>> BLOCK_SIZE_SHIFT);
275 if (blocks != buffers.length) {
276 final AtomicReference<ByteBuffer>[] newBuffers = new AtomicReference[blocks];
277 System.arraycopy(buffers, 0, newBuffers, 0,
278 Math.min(buffers.length, newBuffers.length));
279 for (int i = buffers.length; i < blocks; i++) {
280 newBuffers[i] = new AtomicReference<>(COMPRESSED_EMPTY_BLOCK);
281 }
282 buffers = newBuffers;
283 }
284 compressLaterCache.setCacheSize(Math.max(CACHE_MIN_SIZE, (int) (blocks *
285 compressLaterCachePercent / 100)));
286 }
287
288 /**
289 * Read or write.
290 *
291 * @param pos the position
292 * @param b the byte array
293 * @param off the offset within the byte array
294 * @param len the number of bytes
295 * @param write true for writing
296 * @return the new position
297 */
298 long readWrite(long pos, ByteBuffer b, int off, int len, boolean write) {
299 final java.util.concurrent.locks.Lock lock = write ? rwLock.writeLock()
300 : rwLock.readLock();
301 lock.lock();
302 try {
303
304 long end = pos + len;
305 if (end > length) {
306 if (write) {
307 changeLength(end);
308 } else {
309 len = (int) (length - pos);
310 }
311 }
312 while (len > 0) {
313 final int l = (int) Math.min(len, BLOCK_SIZE - (pos & BLOCK_SIZE_MASK));
314 final int page = (int) (pos >>> BLOCK_SIZE_SHIFT);
315 final ByteBuffer block = expandPage(page);
316 int blockOffset = (int) (pos & BLOCK_SIZE_MASK);
317 if (write) {
318 final ByteBuffer srcTmp = b.slice();
319 final ByteBuffer dstTmp = block.duplicate();
320 srcTmp.position(off);
321 srcTmp.limit(off + l);
322 dstTmp.position(blockOffset);
323 dstTmp.put(srcTmp);
324 } else {
325 // duplicate, so this can be done concurrently
326 final ByteBuffer tmp = block.duplicate();
327 tmp.position(blockOffset);
328 tmp.limit(l + blockOffset);
329 int oldPosition = b.position();
330 b.position(off);
331 b.put(tmp);
332 // restore old position
333 b.position(oldPosition);
334 }
335 if (compress) {
336 addToCompressLaterCache(page);
337 }
338 off += l;
339 pos += l;
340 len -= l;
341 }
342 return pos;
343 } finally {
344 lock.unlock();
345 }
346 }
347
348 /**
349 * Set the file name.
350 *
351 * @param name the name
352 */
353 void setName(String name) {
354 this.name = name;
355 }
356
357 /**
358 * Get the file name
359 *
360 * @return the name
361 */
362 String getName() {
363 return name;
364 }
365
366 /**
367 * Get the last modified time.
368 *
369 * @return the time
370 */
371 long getLastModified() {
372 return lastModified;
373 }
374
375 /**
376 * Check whether writing is allowed.
377 *
378 * @return true if it is
379 */
380 boolean canWrite() {
381 return !isReadOnly;
382 }
383
384 /**
385 * Set the read-only flag.
386 *
387 * @return true
388 */
389 boolean setReadOnly() {
390 isReadOnly = true;
391 return true;
392 }
393
394 }