Repository navigation
Expand file tree
/
Copy pathStoreCached.java
More file actions
500 lines (414 loc) · 17.1 KB
/
Copy pathStoreCached.java
File metadata and controls
500 lines (414 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package org.mapdb;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import static org.mapdb.DataIO.*;
/**
* Extends {@link StoreDirect} with Write Cache
*/
public class StoreCached extends StoreDirect {
/**
* stores modified stack pages.
*/
//TODO only accessed under structural lock, should be LongConcurrentHashMap?
protected final LongObjectMap<byte[]> dirtyStackPages = new LongObjectMap<byte[]>();
protected final LongObjectObjectMap[] writeCache;
protected final static Object TOMBSTONE2 = new Object(){
@Override
public String toString() {
return StoreCached.class.getName()+".TOMBSTONE2";
}
};
protected final int writeQueueSize;
protected final int writeQueueSizePerSegment;
protected final boolean flushInThread;
public StoreCached(
String fileName,
Volume.VolumeFactory volumeFactory,
Cache cache,
int lockScale,
int lockingStrategy,
boolean checksum,
boolean compress,
byte[] password,
boolean readonly,
boolean snapshotEnable,
boolean fileLockDisable,
HeartbeatFileLock fileLockHeartbeat,
ScheduledExecutorService executor,
long startSize,
long sizeIncrement,
boolean recidReuseDisable,
long executorScheduledRate,
final int writeQueueSize) {
super(fileName, volumeFactory, cache,
lockScale,
lockingStrategy,
checksum, compress, password, readonly, snapshotEnable, fileLockDisable, fileLockHeartbeat,
executor,startSize, sizeIncrement, recidReuseDisable);
this.writeQueueSize = writeQueueSize;
this.writeQueueSizePerSegment = writeQueueSize/lockScale;
writeCache = new LongObjectObjectMap[this.lockScale];
for (int i = 0; i < writeCache.length; i++) {
writeCache[i] = new LongObjectObjectMap();
}
flushInThread = this.executor==null &&
writeQueueSize!=0 &&
!(this instanceof StoreWAL); //TODO StoreWAL should dump data into WAL
if(this.executor!=null &&
!(this instanceof StoreWAL) //TODO async write should work for StoreWAL as well
){
for(int i=0;i<this.lockScale;i++){
final int seg = i;
final Lock lock = locks[i].writeLock();
this.executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
lock.lock();
try {
if(writeCache[seg].size>writeQueueSizePerSegment) {
flushWriteCacheSegment(seg);
}
}finally {
lock.unlock();
}
}
},
(long) (executorScheduledRate*Math.random()),
executorScheduledRate,
TimeUnit.MILLISECONDS);
}
}
}
public StoreCached(String fileName) {
this(fileName,
fileName==null? CC.DEFAULT_MEMORY_VOLUME_FACTORY : CC.DEFAULT_FILE_VOLUME_FACTORY,
null,
CC.DEFAULT_LOCK_SCALE,
0,
false, false, null, false, false, false, null,
null, 0L, 0L, false, 0L, 0);
}
@Override
protected void initHeadVol() {
if (CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
if(this.headVol!=null && !this.headVol.isClosed())
headVol.close();
this.headVol = new Volume.SingleByteArrayVol((int) HEAD_END);
vol.transferInto(0,headVol,0,HEAD_END);
}
@Override
protected void longStackPut(long masterLinkOffset, long value, boolean recursive) {
if (CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
if (CC.ASSERT && (masterLinkOffset <= 0 || masterLinkOffset > PAGE_SIZE || masterLinkOffset % 8 != 0))
throw new DBException.DataCorruption("wrong master link");
long masterLinkVal = parity4Get(headVol.getLong(masterLinkOffset));
long pageOffset = masterLinkVal & MOFFSET;
if (masterLinkVal == 0L) {
longStackNewPage(masterLinkOffset, 0L, value);
return;
}
byte[] page = loadLongStackPage(pageOffset, true);
long currSize = masterLinkVal >>> 48;
long prevLinkVal = parity4Get(DataIO.getLong(page, 0));
long pageSize = prevLinkVal >>> 48;
//is there enough space in current page?
if (currSize + 8 >= pageSize) {
//no there is not enough space
//first zero out rest of the page
Arrays.fill(page, (int) currSize, (int) pageSize, (byte) 0);
//allocate new page
longStackNewPage(masterLinkOffset, pageOffset, value);
return;
}
//there is enough space, so just write new value
currSize += DataIO.packLongBidi(page, (int) currSize, longParitySet(value));
//and update master pointer
headVol.putLong(masterLinkOffset, parity4Set(currSize << 48 | pageOffset));
}
@Override
protected long longStackTake(long masterLinkOffset, boolean recursive) {
if (CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
if (CC.ASSERT && (masterLinkOffset < FREE_RECID_STACK ||
masterLinkOffset > FREE_RECID_STACK + round16Up(MAX_REC_SIZE) / 2 ||
masterLinkOffset % 8 != 0))
throw new DBException.DataCorruption("wrong master link");
long masterLinkVal = parity4Get(headVol.getLong(masterLinkOffset));
if (masterLinkVal == 0) {
return 0;
}
long currSize = masterLinkVal >>> 48;
final long pageOffset = masterLinkVal & MOFFSET;
byte[] page = loadLongStackPage(pageOffset,true);
//read packed link from stack
long ret = DataIO.unpackLongBidiReverse(page, (int) currSize);
//extract number of read bytes
long oldCurrSize = currSize;
currSize -= ret >>> 56;
//clear bytes occupied by prev value
Arrays.fill(page, (int) currSize, (int) oldCurrSize, (byte) 0);
//and finally set return value
ret = longParityGet(ret & DataIO.PACK_LONG_RESULT_MASK);
if (CC.ASSERT && currSize < 8)
throw new DBException.DataCorruption("wrong currSize");
//is there space left on current page?
if (currSize > 8) {
//yes, just update master link
headVol.putLong(masterLinkOffset, parity4Set(currSize << 48 | pageOffset));
return ret;
}
//there is no space at current page, so delete current page and update master pointer
long prevPageOffset = parity4Get(DataIO.getLong(page, 0));
final int currPageSize = (int) (prevPageOffset >>> 48);
prevPageOffset &= MOFFSET;
//does previous page exists?
if (prevPageOffset != 0) {
//yes previous page exists
byte[] page2 = loadLongStackPage(prevPageOffset,true);
//find pointer to end of previous page
// (data are packed with var size, traverse from end of page, until zeros
//first read size of current page
currSize = parity4Get(DataIO.getLong(page2, 0)) >>> 48;
//now read bytes from end of page, until they are zeros
while (page2[((int) (currSize - 1))] == 0) {
currSize--;
}
if (CC.ASSERT && currSize < 10)
throw new DBException.DataCorruption("wrong currSize");
} else {
//no prev page does not exist
currSize = 0;
}
//update master link with curr page size and offset
headVol.putLong(masterLinkOffset, parity4Set(currSize << 48 | prevPageOffset));
//release old page, size is stored as part of prev page value
dirtyStackPages.remove(pageOffset);
freeDataPut(pageOffset, currPageSize);
//TODO how TX should handle this
return ret;
}
protected byte[] loadLongStackPage(long pageOffset, boolean willBeModified) {
if (CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
byte[] page = dirtyStackPages.get(pageOffset);
if (page == null) {
int pageSize = (int) (parity4Get(vol.getLong(pageOffset)) >>> 48);
page = new byte[pageSize];
vol.getData(pageOffset, page, 0, pageSize);
if(willBeModified) {
dirtyStackPages.put(pageOffset, page);
}
}
return page;
}
@Override
protected long longStackCount(final long masterLinkOffset){
if(CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
if (CC.ASSERT && (masterLinkOffset <= 0 || masterLinkOffset > PAGE_SIZE || masterLinkOffset % 8 != 0))
throw new DBException.DataCorruption("wrong master link");
long nextLinkVal = DataIO.parity4Get(
headVol.getLong(masterLinkOffset));
long ret = 0;
while(true){
int currSize = (int) (nextLinkVal>>>48);
final long pageOffset = nextLinkVal&MOFFSET;
if(pageOffset==0)
break;
byte[] page = loadLongStackPage(pageOffset, false);
//work on dirty page
while ((page[currSize-1] & 0xFF) == 0) {
currSize--;
}
//iterate from end of page until start of page is reached
while(currSize>8){
long read = DataIO.unpackLongBidiReverse(page,currSize);
//extract number of read bytes
currSize-= read >>>56;
ret++;
}
nextLinkVal = DataIO.parity4Get(
DataIO.getLong(page,0));
}
return ret;
}
@Override
protected void longStackNewPage(long masterLinkOffset, long prevPageOffset, long value) {
if (CC.ASSERT && !structuralLock.isHeldByCurrentThread())
throw new AssertionError();
long newPageOffset = freeDataTakeSingle((int) CHUNKSIZE);
byte[] page = new byte[(int) CHUNKSIZE];
//TODO this is new page, so data should be clear, no need to read them, but perhaps check data are really zero, handle EOF
// vol.getData(newPageOffset, page, 0, page.length);
dirtyStackPages.put(newPageOffset, page);
//write size of current chunk with link to prev page
DataIO.putLong(page, 0, parity4Set((CHUNKSIZE << 48) | prevPageOffset));
//put value
long currSize = 8 + DataIO.packLongBidi(page, 8, longParitySet(value));
//update master pointer
headVol.putLong(masterLinkOffset, parity4Set((currSize << 48) | newPageOffset));
}
@Override
protected void flush() {
if (CC.ASSERT && !commitLock.isHeldByCurrentThread())
throw new AssertionError();
if (isReadOnly())
return;
flushWriteCache();
structuralLock.lock();
try {
//flush modified Long Stack pages
long[] set = dirtyStackPages.set;
for(int i=0;i<set.length;i++){
long offset = set[i];
if(offset==0)
continue;
byte[] val = (byte[]) dirtyStackPages.values[i];
if (CC.ASSERT && offset < PAGE_SIZE)
throw new DBException.DataCorruption("offset to small");
if (CC.ASSERT && val.length % 16 != 0)
throw new AssertionError("not aligned to 16");
if (CC.ASSERT && val.length <= 0 || val.length > MAX_REC_SIZE)
throw new DBException.DataCorruption("wrong length");
vol.putData(offset, val, 0, val.length);
}
dirtyStackPages.clear();
headVol.putLong(LAST_PHYS_ALLOCATED_DATA_OFFSET,parity3Set(lastAllocatedData));
//set header checksum
headVol.putInt(HEAD_CHECKSUM, headChecksum(headVol));
//and flush head
byte[] buf = new byte[(int) HEAD_END]; //TODO copy directly
headVol.getData(0, buf, 0, buf.length);
vol.putData(0, buf, 0, buf.length);
} finally {
structuralLock.unlock();
}
vol.sync();
}
protected void flushWriteCache() {
if (CC.ASSERT && !commitLock.isHeldByCurrentThread())
throw new AssertionError();
//flush modified records
for (int i = 0; i < locks.length; i++) {
Lock lock = locks[i].writeLock();
lock.lock();
try {
flushWriteCacheSegment(i);
} finally {
lock.unlock();
}
}
}
protected void flushWriteCacheSegment(int segment) {
if (CC.ASSERT)
assertWriteLocked(segment);
LongObjectObjectMap writeCache1 = writeCache[segment];
long[] set = writeCache1.set;
Object[] values = writeCache1.values;
for(int i=0;i<set.length;i++){
long recid = set[i];
if(recid==0)
continue;
Object value = values[i*2];
if (value == TOMBSTONE2) {
super.delete2(recid, Serializer.ILLEGAL_ACCESS);
} else {
Serializer s = (Serializer) values[i*2+1];
DataOutputByteArray buf = serialize(value, s); //TODO somehow serialize outside lock?
super.update2(recid, buf);
recycledDataOut.lazySet(buf);
}
}
writeCache1.clear();
if (CC.ASSERT && writeCache[segment].size!=0)
throw new AssertionError();
}
@Override
protected <A> A get2(long recid, Serializer<A> serializer) {
LongObjectObjectMap m = writeCache[lockPos(recid)];
Object cached = m.get1(recid);
if (cached !=null) {
if(cached==TOMBSTONE2)
return null;
return (A) cached;
}
return super.get2(recid, serializer);
}
@Override
protected <A> void delete2(long recid, Serializer<A> serializer) {
if (serializer == null)
throw new NullPointerException();
int lockPos = lockPos(recid);
LongObjectObjectMap map = writeCache[lockPos];
map.put(recid, TOMBSTONE2, null);
if(flushInThread && map.size>writeQueueSize){
flushWriteCacheSegment(lockPos);
}
}
@Override
public <A> long put(A value, Serializer<A> serializer) {
if (serializer == null)
throw new NullPointerException();
//TODO this causes double locking, merge two methods into single method
long recid = preallocate();
update(recid, value, serializer);
return recid;
}
@Override
public <A> void update(long recid, A value, Serializer<A> serializer) {
if (serializer == null)
throw new NullPointerException();
int lockPos = lockPos(recid);
Cache cache = caches==null ? null : caches[lockPos];
Lock lock = locks[lockPos].writeLock();
lock.lock();
try {
if(cache!=null) {
cache.put(recid, value);
}
LongObjectObjectMap map = writeCache[lockPos];
map.put(recid, value, serializer);
if(flushInThread && map.size>writeQueueSizePerSegment){
flushWriteCacheSegment(lockPos);
}
} finally {
lock.unlock();
}
}
@Override
public <A> boolean compareAndSwap(long recid, A expectedOldValue, A newValue, Serializer<A> serializer) {
if(serializer==null)
throw new NullPointerException();
//TODO binary CAS & serialize outside lock
final int lockPos = lockPos(recid);
final Lock lock = locks[lockPos].writeLock();
final Cache cache = caches==null ? null : caches[lockPos];
LongObjectObjectMap<A,Serializer<A>> map = writeCache[lockPos];
lock.lock();
try{
A oldVal = cache==null ? null : (A) cache.get(recid);
if(oldVal == null) {
oldVal = get2(recid, serializer);
}else if(oldVal == Cache.NULL){
oldVal = null;
}
if(oldVal==expectedOldValue || (oldVal!=null && serializer.equals(oldVal,expectedOldValue))){
if(cache!=null) {
cache.put(recid, newValue);
}
map.put(recid,newValue,serializer);
if(flushInThread && map.size>writeQueueSizePerSegment){
flushWriteCacheSegment(lockPos);
}
return true;
}
return false;
}finally {
lock.unlock();
}
}
}