Repository navigation
Expand file tree
/
Copy pathDBMaker.java
More file actions
1606 lines (1386 loc) · 57.5 KB
/
Copy pathDBMaker.java
File metadata and controls
1606 lines (1386 loc) · 57.5 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapdb;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Logger;
/**
* <p>
* A builder class to creare and open new database and individual collections.
* It has several static factory methods.
* Method names depends on type of storage it opens.
* {@code DBMaker}is typically used this way
* </p>
* <pre>
* DB db = DBMaker
* .memoryDB() //static method
* .transactionDisable() //configuration option
* .make() //opens db
* </pre>
*
*
*
* @author Jan Kotek
*/
public final class DBMaker{
protected static final Logger LOG = Logger.getLogger(DBMaker.class.getName());
protected static final String TRUE = "true";
protected interface Keys{
String cache = "cache";
String cacheSize = "cacheSize";
String cache_disable = "disable";
String cache_hashTable = "hashTable";
String cache_hardRef = "hardRef";
String cache_softRef = "softRef";
String cache_weakRef = "weakRef";
String cache_lru = "lru";
String cacheExecutorPeriod = "cacheExecutorPeriod";
String file = "file";
String metrics = "metrics";
String metricsLogInterval = "metricsLogInterval";
String volume = "volume";
String volume_fileChannel = "fileChannel";
String volume_raf = "raf";
String volume_mmapfIfSupported = "mmapfIfSupported";
String volume_mmapf = "mmapf";
String volume_byteBuffer = "byteBuffer";
String volume_directByteBuffer = "directByteBuffer";
String volume_unsafe = "unsafe";
String fileMmapCleanerHack = "fileMmapCleanerHack";
String fileLockDisable = "fileLockDisable";
String fileLockHeartbeatEnable = "fileLockHeartbeatEnable";
String lockScale = "lockScale";
String lock = "lock";
String lock_readWrite = "readWrite";
String lock_single = "single";
String lock_threadUnsafe = "threadUnsafe";
String store = "store";
String store_direct = "direct";
String store_wal = "wal";
String store_append = "append";
String store_heap = "heap";
String storeExecutorPeriod = "storeExecutorPeriod";
String transactionDisable = "transactionDisable";
String asyncWrite = "asyncWrite";
String asyncWriteFlushDelay = "asyncWriteFlushDelay";
String asyncWriteQueueSize = "asyncWriteQueueSize";
String deleteFilesAfterClose = "deleteFilesAfterClose";
String closeOnJvmShutdown = "closeOnJvmShutdown";
String readOnly = "readOnly";
String compression = "compression";
String compression_lzf = "lzf";
String encryptionKey = "encryptionKey";
String encryption = "encryption";
String encryption_xtea = "xtea";
String checksum = "checksum";
String freeSpaceReclaimQ = "freeSpaceReclaimQ";
String commitFileSyncDisable = "commitFileSyncDisable";
String snapshots = "snapshots";
String strictDBGet = "strictDBGet";
String fullTx = "fullTx";
String allocateStartSize = "allocateStartSize";
String allocateIncrement = "allocateIncrement";
String allocateRecidReuseDisable = "allocateRecidReuseDisable";
}
/**
* Creates new in-memory database which stores all data on heap without serialization.
* This mode should be very fast, but data will affect Garbage Collector the same way as traditional Java Collections.
*/
public static Maker heapDB(){
return new Maker()._newHeapDB();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#heapDB()} */
public static Maker newHeapDB(){
return heapDB();
}
/**
* Creates new in-memory database. Changes are lost after JVM exits.
* This option serializes data into {@code byte[]},
* so they are not affected by Garbage Collector.
*/
public static Maker memoryDB(){
return new Maker()._newMemoryDB();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#memoryDB()} */
public static Maker newMemoryDB(){
return memoryDB();
}
/**
* <p>
* Creates new in-memory database. Changes are lost after JVM exits.
* </p><p>
* This will use {@code DirectByteBuffer} outside of HEAP, so Garbage Collector is not affected
* You should increase ammount of direct memory with
* {@code -XX:MaxDirectMemorySize=10G} JVM param
* </p>
*/
public static Maker memoryDirectDB(){
return new Maker()._newMemoryDirectDB();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#memoryDirectDB()} */
public static Maker newMemoryDirectDB(){
return memoryDirectDB();
}
/**
* <p>
* Creates new in-memory database. Changes are lost after JVM exits.
* </p><p>
* This will use {@code sun.misc.Unsafe}. It uses direct-memory access and avoids boundary checking.
* It is bit faster compared to {@code DirectByteBuffer}, but can cause JVM crash in case of error.
* </p><p>
* If {@code sun.misc.Unsafe} is not available for some reason, MapDB will log an warning and fallback into
* {@code DirectByteBuffer} based in-memory store without throwing an exception.
* </p>
*/
public static Maker memoryUnsafeDB(){
return new Maker()._newMemoryUnsafeDB();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#memoryUnsafeDB()} */
public static Maker newMemoryUnsafeDB(){
return memoryUnsafeDB();
}
/**
* Creates or open append-only database stored in file.
* This database uses format other than usual file db
*
* @param file
* @return maker
*/
public static Maker appendFileDB(File file) {
return new Maker()._newAppendFileDB(file);
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#appendFileDB(File)} */
public static Maker newAppendFileDB(File file) {
return appendFileDB(file);
}
/**
* <p>
* Create new BTreeMap backed by temporary file storage.
* This is quick way to create 'throw away' collection.
* </p><p>
*
* Storage is created in temp folder and deleted on JVM shutdown
* </p>
*/
public static <K,V> BTreeMap<K,V> tempTreeMap(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.transactionDisable()
.make()
.treeMapCreate("temp")
.closeEngine()
.make();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#tempTreeMap()} */
public static <K,V> BTreeMap<K,V> newTempTreeMap(){
return tempTreeMap();
}
/**
* <p>
* Create new HTreeMap backed by temporary file storage.
* This is quick way to create 'throw away' collection.
* </p><p>
*
* Storage is created in temp folder and deleted on JVM shutdown
* </p>
*/
public static <K,V> HTreeMap<K,V> tempHashMap(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.transactionDisable()
.make()
.hashMapCreate("temp")
.closeEngine()
.make();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#tempHashMap()} */
public static <K,V> HTreeMap<K,V> newTempHashMap() {
return tempHashMap();
}
/**
* <p>
* Create new TreeSet backed by temporary file storage.
* This is quick way to create 'throw away' collection.
* </p><p>
*
* Storage is created in temp folder and deleted on JVM shutdown
* </p>
*/
public static <K> NavigableSet<K> tempTreeSet(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.transactionDisable()
.make()
.treeSetCreate("temp")
.standalone()
.make();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#tempTreeSet()} */
public static <K> NavigableSet<K> newTempTreeSet(){
return tempTreeSet();
}
/**
* <p>
* Create new HashSet backed by temporary file storage.
* This is quick way to create 'throw away' collection.
* </p><p>
*
* Storage is created in temp folder and deleted on JVM shutdown
* </p>
*/
public static <K> Set<K> tempHashSet(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.transactionDisable()
.make()
.hashSetCreate("temp")
.closeEngine()
.make();
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#tempHashSet()} */
public static <K> Set<K> newTempHashSet(){
return tempHashSet();
}
/**
* Creates new database in temporary folder.
*/
public static Maker tempFileDB() {
try {
return newFileDB(File.createTempFile("mapdb-temp","db"));
} catch (IOException e) {
throw new IOError(e);
}
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#tempFileDB()} */
public static Maker newTempFileDB(){
return tempFileDB();
}
/**
* Creates new off-heap cache with maximal size in GBs.
* Entries are removed from cache in most-recently-used fashion
* if store becomes too big.
*
* This method uses off-heap direct ByteBuffers. See {@link java.nio.ByteBuffer#allocateDirect(int)}
*
* @param size maximal size of off-heap store in gigabytes.
* @return map
*
* @deprecated TODO this method is going to be replaced by something
*/
public static <K,V> HTreeMap<K,V> newCacheDirect(double size){
return DBMaker
.memoryDirectDB()
.transactionDisable()
.make()
.hashMapCreate("cache")
.expireStoreSize(size)
.counterEnable()
.make();
}
/**
* Creates new cache with maximal size in GBs.
* Entries are removed from cache in most-recently-used fashion
* if store becomes too big.
*
* This cache uses on-heap {@code byte[]}, but does not affect GC since objects are serialized into binary form.
* This method uses ByteBuffers backed by on-heap byte[]. See {@link java.nio.ByteBuffer#allocate(int)}
*
* @param size maximal size of off-heap store in gigabytes.
* @return map
* @deprecated TODO this method is going to be replaced by something
*/
public static <K,V> HTreeMap<K,V> newCache(double size){
return DBMaker
.memoryDB()
.transactionDisable()
.make()
.hashMapCreate("cache")
.expireStoreSize(size)
.counterEnable()
.make();
}
/** Creates or open database stored in file. */
public static Maker fileDB(File file){
return new Maker(file);
}
/** @deprecated method renamed, prefix removed, use {@link DBMaker#fileDB(File)} */
public static Maker newFileDB(File file){
return fileDB(file);
}
public static final class Maker {
protected Fun.RecordCondition cacheCondition;
protected ScheduledExecutorService executor;
protected ScheduledExecutorService metricsExecutor;
protected ScheduledExecutorService cacheExecutor;
protected ScheduledExecutorService storeExecutor;
protected Properties props = new Properties();
/** use static factory methods, or make subclass */
protected Maker(){}
protected Maker(File file) {
props.setProperty(Keys.file, file.getPath());
}
public Maker _newHeapDB(){
props.setProperty(Keys.store,Keys.store_heap);
return this;
}
public Maker _newMemoryDB(){
props.setProperty(Keys.volume,Keys.volume_byteBuffer);
return this;
}
public Maker _newMemoryDirectDB() {
props.setProperty(Keys.volume,Keys.volume_directByteBuffer);
return this;
}
public Maker _newMemoryUnsafeDB() {
props.setProperty(Keys.volume,Keys.volume_unsafe);
return this;
}
public Maker _newAppendFileDB(File file) {
props.setProperty(Keys.file, file.getPath());
props.setProperty(Keys.store, Keys.store_append);
return this;
}
public Maker _newFileDB(File file){
props.setProperty(Keys.file, file.getPath());
return this;
}
/**
* Enables background executor
*
* @return this builder
*/
public Maker executorEnable(){
executor = Executors.newScheduledThreadPool(4);
return this;
}
/**
* <p>
* Transaction journal is enabled by default
* You must call <b>DB.commit()</b> to save your changes.
* It is possible to disable transaction journal for better write performance
* In this case all integrity checks are sacrificed for faster speed.
* </p><p>
* If transaction journal is disabled, all changes are written DIRECTLY into store.
* You must call DB.close() method before exit,
* otherwise your store <b>WILL BE CORRUPTED</b>
* </p>
*
* @return this builder
*/
public Maker transactionDisable(){
props.put(Keys.transactionDisable, TRUE);
return this;
}
/**
* Enable metrics, log at info level every 10 SECONDS
*
* @return this builder
*/
public Maker metricsEnable(){
return metricsEnable(CC.DEFAULT_METRICS_LOG_PERIOD);
}
public Maker metricsEnable(long metricsLogPeriod) {
props.put(Keys.metrics, TRUE);
props.put(Keys.metricsLogInterval, ""+metricsLogPeriod);
return this;
}
/**
* Enable separate executor for metrics.
*
* @return this builder
*/
public Maker metricsExecutorEnable(){
return metricsExecutorEnable(
Executors.newSingleThreadScheduledExecutor());
}
/**
* Enable separate executor for metrics.
*
* @return this builder
*/
public Maker metricsExecutorEnable(ScheduledExecutorService metricsExecutor){
this.metricsExecutor = metricsExecutor;
return this;
}
/**
* Enable separate executor for cache.
*
* @return this builder
*/
public Maker cacheExecutorEnable(){
return cacheExecutorEnable(
Executors.newSingleThreadScheduledExecutor());
}
/**
* Enable separate executor for cache.
*
* @return this builder
*/
public Maker cacheExecutorEnable(ScheduledExecutorService metricsExecutor){
this.cacheExecutor = metricsExecutor;
return this;
}
/**
* Sets interval in which executor should check cache
*
* @param period in ms
* @return this builder
*/
public Maker cacheExecutorPeriod(long period){
props.put(Keys.cacheExecutorPeriod, ""+period);
return this;
}
/**
* Enable separate executor for store (async write, compaction)
*
* @return this builder
*/
public Maker storeExecutorEnable(){
return storeExecutorEnable(
Executors.newScheduledThreadPool(4));
}
/**
* Enable separate executor for cache.
*
* @return this builder
*/
public Maker storeExecutorEnable(ScheduledExecutorService metricsExecutor){
this.storeExecutor = metricsExecutor;
return this;
}
/**
* Sets interval in which executor should check cache
*
* @param period in ms
* @return this builder
*/
public Maker storeExecutorPeriod(long period){
props.put(Keys.storeExecutorPeriod, ""+period);
return this;
}
/**
* Install callback condition, which decides if some record is to be included in cache.
* Condition should return {@code true} for every record which should be included
*
* This could be for example useful to include only BTree Directory Nodes and leave values and Leaf nodes outside of cache.
*
* !!! Warning:!!!
*
* Cache requires **consistent** true or false. Failing to do so will result in inconsitent cache and possible data corruption.
* Condition is also executed several times, so it must be very fast
*
* You should only use very simple logic such as {@code value instanceof SomeClass}.
*
* @return this builder
*/
public Maker cacheCondition(Fun.RecordCondition cacheCondition){
this.cacheCondition = cacheCondition;
return this;
}
/**
/**
* Disable cache if enabled. Cache is disabled by default, so this method has no longer purpose.
*
* @return this builder
* @deprecated cache is disabled by default
*/
public Maker cacheDisable(){
props.put(Keys.cache,Keys.cache_disable);
return this;
}
/**
* <p>
* Enables unbounded hard reference cache.
* This cache is good if you have lot of available memory.
* </p><p>
*
* All fetched records are added to HashMap and stored with hard reference.
* To prevent OutOfMemoryExceptions MapDB monitors free memory,
* if it is bellow 25% cache is cleared.
* </p>
*
* @return this builder
*/
public Maker cacheHardRefEnable(){
props.put(Keys.cache, Keys.cache_hardRef);
return this;
}
/**
* <p>
* Set cache size. Interpretations depends on cache type.
* For fixed size caches (such as FixedHashTable cache) it is maximal number of items in cache.
* </p><p>
*
* For unbounded caches (such as HardRef cache) it is initial capacity of underlying table (HashMap).
* <p></p>
*
* Default cache size is 2048.
* <p>
*
* @param cacheSize new cache size
* @return this builder
*/
public Maker cacheSize(int cacheSize){
props.setProperty(Keys.cacheSize, "" + cacheSize);
return this;
}
/**
* <p>
* Fixed size cache which uses hash table.
* Is thread-safe and requires only minimal locking.
* Items are randomly removed and replaced by hash collisions.
* </p><p>
*
* This is simple, concurrent, small-overhead, random cache.
* </p>
*
* @return this builder
*/
public Maker cacheHashTableEnable(){
props.put(Keys.cache, Keys.cache_hashTable);
return this;
}
/**
* <p>
* Fixed size cache which uses hash table.
* Is thread-safe and requires only minimal locking.
* Items are randomly removed and replaced by hash collisions.
* </p><p>
*
* This is simple, concurrent, small-overhead, random cache.
* </p>
*
* @param cacheSize new cache size
* @return this builder
*/
public Maker cacheHashTableEnable(int cacheSize){
props.put(Keys.cache, Keys.cache_hashTable);
props.setProperty(Keys.cacheSize, "" + cacheSize);
return this;
}
/**
* Enables unbounded cache which uses <code>WeakReference</code>.
* Items are removed from cache by Garbage Collector
*
* @return this builder
*/
public Maker cacheWeakRefEnable(){
props.put(Keys.cache, Keys.cache_weakRef);
return this;
}
/**
* Enables unbounded cache which uses <code>SoftReference</code>.
* Items are removed from cache by Garbage Collector
*
* @return this builder
*/
public Maker cacheSoftRefEnable(){
props.put(Keys.cache, Keys.cache_softRef);
return this;
}
/**
* Enables Least Recently Used cache. It is fixed size cache and it removes less used items to make space.
*
* @return this builder
*/
public Maker cacheLRUEnable(){
props.put(Keys.cache,Keys.cache_lru);
return this;
}
/**
* <p>
* Disable locks. This will make MapDB thread unsafe. It will also disable any background thread workers.
* </p><p>
*
* <b>WARNING: </b> this option is dangerous. With locks disabled multi-threaded access could cause data corruption and causes.
* MapDB does not have fail-fast iterator or any other means of protection
* </p>
*
* @return this builder
*/
public Maker lockDisable() {
props.put(Keys.lock, Keys.lock_threadUnsafe);
return this;
}
/**
* <p>
* Disables double read-write locks and enables single read-write locks.
* </p><p>
*
* This type of locking have smaller overhead and can be faster in mostly-write scenario.
* </p>
* @return this builder
*/
public Maker lockSingleEnable() {
props.put(Keys.lock, Keys.lock_single);
return this;
}
/**
* <p>
* Sets concurrency scale. More locks means better scalability with multiple cores, but also higher memory overhead
* </p><p>
*
* This value has to be power of two, so it is rounded up automatically.
* </p>
*
* @return this builder
*/
public Maker lockScale(int scale) {
props.put(Keys.lockScale, "" + scale);
return this;
}
/**
*@deprecated renamed to {@link #fileMmapEnable()}
*/
public Maker mmapFileEnable() {
return fileMmapEnable();
}
/**
* <p>
* Enables Memory Mapped Files, much faster storage option. However on 32bit JVM this mode could corrupt
* your DB thanks to 4GB memory addressing limit.
* </p><p>
*
* You may experience {@code java.lang.OutOfMemoryError: Map failed} exception on 32bit JVM, if you enable this
* mode.
* </p>
*/
public Maker fileMmapEnable() {
assertNotInMemoryVolume();
props.setProperty(Keys.volume, Keys.volume_mmapf);
return this;
}
/**
* <p>
* Enables cleaner hack to close mmaped files at DB.close(), rather than Garbage Collection.
* See relevant <a href="http://bugs.java.com/view_bug.do?bug_id=4724038">JVM bug</a>.
* Please note that this option closes files, but could cause all sort of problems,
* including JVM crash.
* </p><p>
* Memory mapped files in Java are not unmapped when file closes.
* Unmapping happens when {@code DirectByteBuffer} is garbage collected.
* Delay between file close and GC could be very long, possibly even hours.
* This causes file descriptor to remain open, causing all sort of problems:
* </p><p>
* On Windows opened file can not be deleted or accessed by different process.
* It remains locked even after JVM process exits until Windows restart.
* This is causing problems during compaction etc.
* </p><p>
* On Linux (and other systems) opened files consumes file descriptor. Eventually
* JVM process could run out of available file descriptors (couple of thousands)
* and would be unable to open new files or sockets.
* </p><p>
* On Oracle and OpenJDK JVMs there is option to unmap files after closing.
* However it is not officially supported and could result in all sort of strange behaviour.
* In MapDB it was linked to <a href="https://github.com/jankotek/mapdb/issues/442">JVM crashes</a>,
* and was disabled by default in MapDB 2.0.
* </p>
* @return this builder
*/
public Maker fileMmapCleanerHackEnable() {
props.setProperty(Keys.fileMmapCleanerHack,TRUE);
return this;
}
/**
* <p>
* MapDB needs exclusive lock over storage file it is using.
* When single file is used by multiple DB instances at the same time, storage file gets quickly corrupted.
* To prevent multiple opening MapDB uses {@link FileChannel#lock()}.
* If file is already locked, opening it fails with {@link DBException.FileLocked}
* </p><p>
* In some cases file might remain locked, if DB is not closed correctly or JVM crashes.
* This option disables exclusive file locking. Use it if you have troubles to reopen files
*
* </p>
* @return this builder
*/
public Maker fileLockDisable() {
props.setProperty(Keys.fileLockDisable,TRUE);
return this;
}
/**
* <p>
* MapDB needs exclusive lock over storage file it is using.
* When single file is used by multiple DB instances at the same time, storage file gets quickly corrupted.
* To prevent multiple opening MapDB uses {@link FileChannel#lock()}.
* If file is already locked, opening it fails with {@link DBException.FileLocked}
* </p><p>
* In some cases file might remain locked, if DB is not closed correctly or JVM crashes.
* This option replaces {@link FileChannel#lock()} exclusive file locking with {@code *.lock} file.
* This file is periodically updated by background thread. If JVM dies, the lock file gets old
* and eventually expires. Use it if you have troubles to reopen files.
* </p><p>
* This method was taken from <a href="http://www.h2database.com/">H2 database</a>.
* It was originally written by Thomas Mueller and modified for MapDB purposes.
* </p><p>
* Original description from H2 documentation:
* </p><ul>
* <li>If the lock file does not exist, it is created (using the atomic operation <code>File.createNewFile</code>).
* Then, the process waits a little bit (20 ms) and checks the file again. If the file was changed during this time,
* the operation is aborted. This protects against a race condition when one process deletes the lock file just after
* another one create it, and a third process creates the file again. It does not occur if there are only
* two writers. </li>
* <li> If the file can be created, a random number is inserted together with the locking method ('file').
* Afterwards, a watchdog thread is started that checks regularly (every second once by default)
* if the file was deleted or modified by another (challenger) thread / process. Whenever that occurs,
* the file is overwritten with the old data. The watchdog thread runs with high priority so that a change
* to the lock file does not get through undetected even if the system is very busy. However, the watchdog
* thread does use very little resources (CPU time), because it waits most of the time. Also, the watchdog
* only reads from the hard disk and does not write to it. </li>
* <li> If the lock file exists and was recently
* modified, the process waits for some time (up to two seconds). If it was still changed, an exception is thrown
* (database is locked). This is done to eliminate race conditions with many concurrent writers. Afterwards,
* the file is overwritten with a new version (challenge). After that, the thread waits for 2 seconds.
* If there is a watchdog thread protecting the file, he will overwrite the change and this process will fail
* to lock the database. However, if there is no watchdog thread, the lock file will still be as written by
* this thread. In this case, the file is deleted and atomically created again. The watchdog thread is started
* in this case and the file is locked. </li>
* </ul>
* <p> This algorithm is tested with over 100 concurrent threads. In some cases, when there are many concurrent
* threads trying to lock the database, they block each other (meaning the file cannot be locked by any of them)
* for some time. However, the file never gets locked by two threads at the same time. However using that many
* concurrent threads / processes is not the common use case. Generally, an application should throw an error
* to the user if it cannot open a database, and not try again in a (fast) loop. </p>
*
* @return this builder
*/
public Maker fileLockHeartbeatEnable() {
props.setProperty(Keys.fileLockHeartbeatEnable,TRUE);
return this;
}
private void assertNotInMemoryVolume() {
if(Keys.volume_byteBuffer.equals(props.getProperty(Keys.volume)) ||
Keys.volume_directByteBuffer.equals(props.getProperty(Keys.volume)))
throw new IllegalArgumentException("Can not enable mmap file for in-memory store");
}
/**
*
* @return this
* @deprecated mapdb 2.0 uses single file, no partial mapping possible
*/
public Maker mmapFileEnablePartial() {
return this;
}
/**
* Enable Memory Mapped Files only if current JVM supports it (is 64bit).
* @deprecated renamed to {@link #fileMmapEnableIfSupported()}
*/
public Maker mmapFileEnableIfSupported() {
return fileMmapEnableIfSupported();
}
/**
* Enable Memory Mapped Files only if current JVM supports it (is 64bit).
*/
public Maker fileMmapEnableIfSupported() {
assertNotInMemoryVolume();
props.setProperty(Keys.volume,Keys.volume_mmapfIfSupported);
return this;
}
/**
* Enable FileChannel access. By default MapDB uses {@link java.io.RandomAccessFile}.
* whic is slower and more robust. but does not allow concurrent access (parallel read and writes). RAF is still thread-safe
* but has global lock.
* FileChannel does not have global lock, and is faster compared to RAF. However memory-mapped files are
* probably best choice.
*/
public Maker fileChannelEnable() {
assertNotInMemoryVolume();
props.setProperty(Keys.volume,Keys.volume_fileChannel);
return this;
}
/**
* MapDB supports snapshots. {@code TxEngine} requires additional locking which has small overhead when not used.
* Snapshots are disabled by default. This option switches the snapshots on.
*
* @return this builder
*/
public Maker snapshotEnable(){
props.setProperty(Keys.snapshots,TRUE);
return this;
}
/**
* <p>
* Enables mode where all modifications are queued and written into disk on Background Writer Thread.
* So all modifications are performed in asynchronous mode and do not block.
* </p><p>
*
* Enabling this mode might increase performance for single threaded apps.
* </p>
*
* @return this builder
*/
public Maker asyncWriteEnable(){
props.setProperty(Keys.asyncWrite,TRUE);
return this;
}
/**
* <p>
* Set flush interval for write cache, by default is 0
* </p><p>
* When BTreeMap is constructed from ordered set, tree node size is increasing linearly with each
* item added. Each time new key is added to tree node, its size changes and
* storage needs to find new place. So constructing BTreeMap from ordered set leads to large
* store fragmentation.
* </p><p>
*
* Setting flush interval is workaround as BTreeMap node is always updated in memory (write cache)
* and only final version of node is stored on disk.
* </p>
*
* @param delay flush write cache every N miliseconds
* @return this builder
*/
public Maker asyncWriteFlushDelay(int delay){
props.setProperty(Keys.asyncWriteFlushDelay,""+delay);
return this;
}
/**
* <p>
* Set size of async Write Queue. Default size is
* </p><p>
* Using too large queue size can lead to out of memory exception.
* </p>