Repository navigation
Expand file tree
/
Copy pathDB.java
More file actions
2671 lines (2297 loc) · 96.7 KB
/
Copy pathDB.java
File metadata and controls
2671 lines (2297 loc) · 96.7 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.Closeable;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A database with easy access to named maps and other collections.
*
* @author Jan Kotek
*/
//TODO DB uses global lock, replace it with ReadWrite lock or fine grained locking.
@SuppressWarnings("unchecked")
public class DB implements Closeable {
protected static final Logger LOG = Logger.getLogger(DB.class.getName());
public static final String METRICS_DATA_WRITE = "data.write";
public static final String METRICS_RECORD_WRITE = "record.write";
public static final String METRICS_DATA_READ = "data.read";
public static final String METRICS_RECORD_READ = "record.read";
public static final String METRICS_CACHE_HIT = "cache.hit";
public static final String METRICS_CACHE_MISS = "cache.miss";
protected final boolean strictDBGet;
protected final boolean deleteFilesAfterClose;
/** Engine which provides persistence for this DB*/
protected Engine engine;
/** already loaded named collections. It is important to keep collections as singletons, because of 'in-memory' locking*/
protected Map<String, WeakReference<?>> namesInstanciated = new HashMap<String, WeakReference<?>>();
protected Map<IdentityWrapper, String> namesLookup =
new ConcurrentHashMap<IdentityWrapper, String>();
/** view over named records */
protected SortedMap<String, Object> catalog;
protected ScheduledExecutorService executor = null;
protected SerializerPojo serializerPojo;
protected ScheduledExecutorService metricsExecutor;
protected ScheduledExecutorService storeExecutor;
protected ScheduledExecutorService cacheExecutor;
protected final Set<String> unknownClasses = new ConcurrentSkipListSet<String>();
//TODO collection get/create should be under consistencyLock.readLock()
protected final ReadWriteLock consistencyLock;
/** changes object hash and equals method to use identity */
protected static class IdentityWrapper{
final Object o;
public IdentityWrapper(Object o) {
this.o = o;
}
@Override
public int hashCode() {
return System.identityHashCode(o);
}
@Override
public boolean equals(Object v) {
return ((IdentityWrapper)v).o==o;
}
}
/**
* Construct new DB. It is just thin layer over {@link Engine} which does the real work.
* @param engine
*/
public DB(final Engine engine){
this(engine,false,false, null, false, null, 0, null, null);
}
public DB(
final Engine engine,
boolean strictDBGet,
boolean deleteFilesAfterClose,
ScheduledExecutorService executor,
boolean lockDisable,
ScheduledExecutorService metricsExecutor,
long metricsLogInterval,
ScheduledExecutorService storeExecutor,
ScheduledExecutorService cacheExecutor
) {
//TODO investigate dereference and how non-final field affect performance. Perhaps abandon dereference completely
// if(!(engine instanceof EngineWrapper)){
// //access to Store should be prevented after `close()` was called.
// //So for this we have to wrap raw Store into EngineWrapper
// engine = new EngineWrapper(engine);
// }
this.engine = engine;
this.strictDBGet = strictDBGet;
this.deleteFilesAfterClose = deleteFilesAfterClose;
this.executor = executor;
this.consistencyLock = lockDisable ?
new Store.ReadWriteSingleLock(Store.NOLOCK) :
new ReentrantReadWriteLock();
this.metricsExecutor = metricsExecutor==null ? executor : metricsExecutor;
this.storeExecutor = storeExecutor;
this.cacheExecutor = cacheExecutor;
serializerPojo = new SerializerPojo(
//get name for given object
new Fun.Function1<String, Object>() {
@Override
public String run(Object o) {
if(o==DB.this)
return "$$DB_OBJECT_Q!#!@#!#@9009a09sd";
return getNameForObject(o);
}
},
//get object with given name
new Fun.Function1<Object, String>() {
@Override
public Object run(String name) {
Object ret = get(name);
if(ret == null && "$$DB_OBJECT_Q!#!@#!#@9009a09sd".equals(name))
return DB.this;
return ret;
}
},
//load class catalog
new Fun.Function1Int<SerializerPojo.ClassInfo>() {
@Override
public SerializerPojo.ClassInfo run(int index) {
long[] classInfoRecids = DB.this.engine.get(Engine.RECID_CLASS_CATALOG, Serializer.RECID_ARRAY);
if(classInfoRecids==null || index<0 || index>=classInfoRecids.length)
return null;
return getEngine().get(classInfoRecids[index], SerializerPojo.CLASS_INFO_SERIALIZER);
}
},
new Fun.Function0<SerializerPojo.ClassInfo[]>() {
@Override
public SerializerPojo.ClassInfo[] run() {
long[] classInfoRecids = engine.get(Engine.RECID_CLASS_CATALOG, Serializer.RECID_ARRAY);
SerializerPojo.ClassInfo[] ret = new SerializerPojo.ClassInfo[classInfoRecids==null?0:classInfoRecids.length];
for(int i=0;i<ret.length;i++){
ret[i] = engine.get(classInfoRecids[i],SerializerPojo.CLASS_INFO_SERIALIZER);
}
return ret;
}
},
//notify DB than given class is missing in catalog and should be added on next commit.
new Fun.Function1<Void, String>() {
@Override public Void run(String className) {
unknownClasses.add(className);
return null;
}
},
engine);
reinit();
if(metricsExecutor!=null && metricsLogInterval!=0){
if(!CC.METRICS_CACHE){
LOG.warning("MapDB was compiled without cache metrics. No cache hit/miss will be reported");
}
metricsExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
metricsLog();
}
}, metricsLogInterval, metricsLogInterval, TimeUnit.MILLISECONDS);
}
}
public void metricsLog() {
Map metrics = DB.this.metricsGet();
String s = metrics.toString();
LOG.info("Metrics: "+s);
}
public Map<String,Long> metricsGet() {
Map ret = new TreeMap();
Store s = Store.forEngine(engine);
s.metricsCollect(ret);
return Collections.unmodifiableMap(ret);
}
protected void reinit() {
//open name dir
//$DELAY$
catalog = BTreeMap.preinitCatalog(this);
}
public <A> A catGet(String name, A init){
if(CC.ASSERT && ! (Thread.holdsLock(DB.this)))
throw new AssertionError();
A ret = (A) catalog.get(name);
return ret!=null? ret : init;
}
public <A> A catGet(String name){
if(CC.ASSERT && ! (Thread.holdsLock(DB.this)))
throw new AssertionError();
//$DELAY$
return (A) catalog.get(name);
}
public <A> A catPut(String name, A value){
if(CC.ASSERT && ! (Thread.holdsLock(DB.this)))
throw new AssertionError();
//$DELAY$
catalog.put(name, value);
return value;
}
public <A> A catPut(String name, A value, A retValueIfNull){
if(CC.ASSERT && ! (Thread.holdsLock(DB.this)))
throw new AssertionError();
if(value==null) return retValueIfNull;
//$DELAY$
catalog.put(name, value);
return value;
}
/**
* Get name for object. DB keeps weak reference to all objects it instanciated
*
* @param obj object to get name for
* @return name for this object, if it has name and was instanciated by this DB
*/
public String getNameForObject(Object obj) {
return namesLookup.get(new IdentityWrapper(obj));
}
static public class HTreeMapMaker{
protected final DB db;
protected final String name;
protected final Engine[] engines;
public HTreeMapMaker(DB db, String name, Engine[] engines) {
this.db = db;
this.name = name;
this.engines = engines;
this.executor = db.executor;
}
protected boolean counter = false;
protected Serializer<?> keySerializer = null;
protected Serializer<?> valueSerializer = null;
protected long expireMaxSize = 0L;
protected long expire = 0L;
protected long expireAccess = 0L;
protected long expireStoreSize;
protected Bind.MapWithModificationListener ondisk;
protected boolean ondiskOverwrite;
protected Fun.Function1<?,?> valueCreator = null;
protected Iterator pumpSource;
protected Fun.Function1 pumpKeyExtractor;
protected Fun.Function1 pumpValueExtractor;
protected int pumpPresortBatchSize = (int) 1e7;
protected boolean pumpIgnoreDuplicates = false;
protected boolean closeEngine = false;
protected ScheduledExecutorService executor;
protected long executorPeriod = CC.DEFAULT_HTREEMAP_EXECUTOR_PERIOD;
/** by default collection does not have counter, without counter updates are faster, but entire collection needs to be traversed to count items.*/
public HTreeMapMaker counterEnable(){
this.counter = true;
return this;
}
/** keySerializer used to convert keys into/from binary form. */
public HTreeMapMaker keySerializer(Serializer<?> keySerializer){
this.keySerializer = keySerializer;
return this;
}
/** valueSerializer used to convert values into/from binary form. */
public HTreeMapMaker valueSerializer(Serializer<?> valueSerializer){
this.valueSerializer = valueSerializer;
return this;
}
/** maximal number of entries in this map. Less used entries will be expired and removed to make collection smaller */
public HTreeMapMaker expireMaxSize(long maxSize){
this.expireMaxSize = maxSize;
this.counter = true;
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. */
public HTreeMapMaker expireAfterWrite(long interval, TimeUnit timeUnit){
this.expire = timeUnit.toMillis(interval);
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. */
public HTreeMapMaker expireAfterWrite(long interval){
this.expire = interval;
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all map read and write operations */
public HTreeMapMaker expireAfterAccess(long interval, TimeUnit timeUnit){
this.expireAccess = timeUnit.toMillis(interval);
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all map read and write operations */
public HTreeMapMaker expireAfterAccess(long interval){
this.expireAccess = interval;
return this;
}
/** maximal size of store in GB, if store is larger entries will start expiring */
public HTreeMapMaker expireStoreSize(double maxStoreSize) {
this.expireStoreSize = (long) (maxStoreSize*1024L*1024L*1024L);
return this;
}
/**
* After expiration (or deletion), put entries into given map
*
* @param ondisk Map populated with data after expiration
* @param overwrite if true any data in onDisk will be overwritten.
* If false only non-existing keys will be inserted
* ({@code put() versus putIfAbsent()};
*
* @return this builder
*/
public HTreeMapMaker expireOverflow(Bind.MapWithModificationListener ondisk, boolean overwrite){
this.ondisk = ondisk;
this.ondiskOverwrite = overwrite;
return this;
}
/** If value is not found, HTreeMap can fetch and insert default value. {@code valueCreator} is used to return new value.
* This way {@code HTreeMap.get()} never returns null */
public HTreeMapMaker valueCreator(Fun.Function1<?,?> valueCreator){
this.valueCreator = valueCreator;
return this;
}
public <K,V> HTreeMapMaker pumpSource(Iterator<K> keysSource, Fun.Function1<V,K> valueExtractor){
this.pumpSource = keysSource;
this.pumpKeyExtractor = Fun.extractNoTransform();
this.pumpValueExtractor = valueExtractor;
return this;
}
public <K,V> HTreeMapMaker pumpSource(Iterator<Fun.Pair<K,V>> entriesSource){
this.pumpSource = entriesSource;
this.pumpKeyExtractor = Fun.extractKey();
this.pumpValueExtractor = Fun.extractValue();
return this;
}
public HTreeMapMaker pumpPresort(int batchSize){
this.pumpPresortBatchSize = batchSize;
return this;
}
public HTreeMapMaker executorEnable(){
return executorEnable(Executors.newSingleThreadScheduledExecutor());
}
public HTreeMapMaker executorEnable(ScheduledExecutorService executor) {
this.executor = executor;
return this;
}
public HTreeMapMaker executorPeriod(long period){
this.executorPeriod = period;
return this;
}
/**
* If source iteretor contains an duplicate key, exception is thrown.
* This options will only use firts key and ignore any consequentive duplicates.
*/
public <K> HTreeMapMaker pumpIgnoreDuplicates(){
this.pumpIgnoreDuplicates = true;
return this;
}
protected HTreeMapMaker closeEngine() {
closeEngine = true;
return this;
}
public <K,V> HTreeMap<K,V> make(){
if(expireMaxSize!=0) counter =true;
return db.hashMapCreate(HTreeMapMaker.this);
}
public <K,V> HTreeMap<K,V> makeOrGet(){
//$DELAY$
synchronized (db){
//TODO add parameter check
//$DELAY$
return (HTreeMap<K, V>) (db.catGet(name+".type")==null?
make():
db.hashMap(name,keySerializer,valueSerializer,(Fun.Function1)valueCreator));
}
}
}
public class HTreeSetMaker{
protected final String name;
public HTreeSetMaker(String name) {
this.name = name;
}
protected boolean counter = false;
protected Serializer<?> serializer = null;
protected long expireMaxSize = 0L;
protected long expireStoreSize = 0L;
protected long expire = 0L;
protected long expireAccess = 0L;
protected Iterator pumpSource;
protected int pumpPresortBatchSize = (int) 1e7;
protected boolean pumpIgnoreDuplicates = false;
protected boolean closeEngine = false;
protected ScheduledExecutorService executor = DB.this.executor;
protected long executorPeriod = CC.DEFAULT_HTREEMAP_EXECUTOR_PERIOD;
/** by default collection does not have counter, without counter updates are faster, but entire collection needs to be traversed to count items.*/
public HTreeSetMaker counterEnable(){
this.counter = true;
return this;
}
/** keySerializer used to convert keys into/from binary form. */
public HTreeSetMaker serializer(Serializer<?> serializer){
this.serializer = serializer;
return this;
}
/** maximal number of entries in this map. Less used entries will be expired and removed to make collection smaller */
public HTreeSetMaker expireMaxSize(long maxSize){
this.expireMaxSize = maxSize;
this.counter = true;
return this;
}
/** maximal size of store in GB, if store is larger entries will start expiring */
public HTreeSetMaker expireStoreSize(double maxStoreSize){
this.expireStoreSize = (long) (maxStoreSize * 1024L * 1024L * 1024L);
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. */
public HTreeSetMaker expireAfterWrite(long interval, TimeUnit timeUnit){
this.expire = timeUnit.toMillis(interval);
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. */
public HTreeSetMaker expireAfterWrite(long interval){
this.expire = interval;
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all map read and write operations */
public HTreeSetMaker expireAfterAccess(long interval, TimeUnit timeUnit){
this.expireAccess = timeUnit.toMillis(interval);
return this;
}
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all map read and write operations */
public HTreeSetMaker expireAfterAccess(long interval){
this.expireAccess = interval;
return this;
}
public HTreeSetMaker pumpSource(Iterator<?> source){
this.pumpSource = source;
return this;
}
/**
* If source iteretor contains an duplicate key, exception is thrown.
* This options will only use firts key and ignore any consequentive duplicates.
*/
public HTreeSetMaker pumpIgnoreDuplicates(){
this.pumpIgnoreDuplicates = true;
return this;
}
public HTreeSetMaker pumpPresort(int batchSize){
this.pumpPresortBatchSize = batchSize;
return this;
}
public HTreeSetMaker executorEnable(){
return executorEnable(Executors.newSingleThreadScheduledExecutor());
}
public HTreeSetMaker executorEnable(ScheduledExecutorService executor) {
this.executor = executor;
return this;
}
public HTreeSetMaker executorPeriod(long period){
this.executorPeriod = period;
return this;
}
protected HTreeSetMaker closeEngine() {
this.closeEngine = true;
return this;
}
public <K> Set<K> make(){
if(expireMaxSize!=0) counter =true;
return DB.this.hashSetCreate(HTreeSetMaker.this);
}
public <K> Set<K> makeOrGet(){
synchronized (DB.this){
//$DELAY$
//TODO add parameter check
return (Set<K>) (catGet(name+".type")==null?
make(): hashSet(name,serializer));
}
}
}
/**
* @deprecated method renamed, use {@link DB#hashMap(String)}
*/
synchronized public <K,V> HTreeMap<K,V> getHashMap(String name){
return hashMap(name);
}
/**
* Opens existing or creates new Hash Tree Map.
* This collection perform well under concurrent access.
* Is best for large keys and large values.
*
* @param name of the map
* @return map
*/
synchronized public <K,V> HTreeMap<K,V> hashMap(String name){
return hashMap(name, null, null, null);
}
/**
* @deprecated method renamed, use {@link DB#hashMap(String,Serializer, Serializer, org.mapdb.Fun.Function1)}
*/
synchronized public <K,V> HTreeMap<K,V> getHashMap(String name, Fun.Function1<V,K> valueCreator){
return hashMap(name, null, null, valueCreator);
}
/**
* Opens existing or creates new Hash Tree Map.
* This collection perform well under concurrent access.
* Is best for large keys and large values.
*
* @param name of map
* @param valueCreator if value is not found, new is created and placed into map.
* @return map
*/
synchronized public <K,V> HTreeMap<K,V> hashMap(
String name,
Serializer<K> keySerializer,
Serializer<V> valueSerializer,
Fun.Function1<V, K> valueCreator){
checkNotClosed();
HTreeMap<K,V> ret = (HTreeMap<K, V>) getFromWeakCollection(name);
if(ret!=null) return ret;
String type = catGet(name + ".type", null);
//$DELAY$
if(type==null){
//$DELAY$
checkShouldCreate(name);
if(engine.isReadOnly()){
Engine e = new StoreHeap(true,1,0,false);
//$DELAY$
new DB(e).hashMap("a");
return namedPut(name,
new DB(new Engine.ReadOnlyWrapper(e)).hashMap("a"));
}
HTreeMapMaker m = hashMapCreate(name);
if(valueCreator!=null)
m = m.valueCreator(valueCreator);
if(keySerializer!=null)
m = m.keySerializer(keySerializer);
if(valueSerializer!=null)
m = m.valueSerializer(valueSerializer);
return m.make();
}
//check type
checkType(type, "HashMap");
Object keySer2 = catGet(name+".keySerializer");
if(keySerializer!=null){
if(keySer2!=Fun.PLACEHOLDER && keySer2!=keySerializer){
LOG.warning("Map '"+name+"' has keySerializer defined in Name Catalog, but other serializer was passed as constructor argument. Using one from constructor argument.");
}
keySer2 = keySerializer;
}
if(keySer2==Fun.PLACEHOLDER){
throw new DBException.UnknownSerializer("Map '"+name+"' has no keySerializer defined in Name Catalog nor constructor argument.");
}
Object valSer2 = catGet(name+".valueSerializer");
if(valueSerializer!=null){
if(valSer2!=Fun.PLACEHOLDER && valSer2!=valueSerializer){
LOG.warning("Map '"+name+"' has valueSerializer defined in name catalog, but other serializer was passed as constructor argument. Using one from constructor argument.");
}
valSer2 = valueSerializer;
}
if(valSer2==Fun.PLACEHOLDER) {
throw new DBException.UnknownSerializer("Map '" + name + "' has no valueSerializer defined in Name Catalog nor constructor argument.");
}
//open existing map
//$DELAY$
ret = new HTreeMap<K,V>(
HTreeMap.fillEngineArray(engine),
false,
(long[])catGet(name+".counterRecids"),
(Integer)catGet(name+".hashSalt"),
(long[])catGet(name+".segmentRecids"),
(Serializer<K>)keySer2,
(Serializer<V>)valSer2,
catGet(name+".expireTimeStart",0L),
catGet(name+".expire",0L),
catGet(name+".expireAccess",0L),
catGet(name+".expireMaxSize",0L),
catGet(name+".expireStoreSize",0L),
(long[])catGet(name+".expireHeads",null),
(long[])catGet(name+".expireTails",null),
valueCreator,
executor,
CC.DEFAULT_HTREEMAP_EXECUTOR_PERIOD,
false,
consistencyLock.readLock()
);
//$DELAY$
namedPut(name, ret);
//$DELAY$
return ret;
}
public <V> V namedPut(String name, Object ret) {
//$DELAY$
namesInstanciated.put(name, new WeakReference<Object>(ret));
//$DELAY$
namesLookup.put(new IdentityWrapper(ret), name);
return (V) ret;
}
/**
* @deprecated method renamed, use {@link DB#hashMapCreate(String)}
*/
public HTreeMapMaker createHashMap(String name){
return hashMapCreate(name);
}
/**
* Returns new builder for HashMap with given name
*
* @param name of map to create
* @throws IllegalArgumentException if name is already used
* @return maker, call {@code .make()} to create map
*/
public HTreeMapMaker hashMapCreate(String name){
return new HTreeMapMaker(DB.this, name, HTreeMap.fillEngineArray(engine));
}
/**
* Creates new HashMap with more specific arguments
*
* @throws IllegalArgumentException if name is already used
* @return newly created map
*/
synchronized protected <K,V> HTreeMap<K,V> hashMapCreate(HTreeMapMaker m){
String name = m.name;
checkNameNotExists(name);
//$DELAY$
long expireTimeStart=0, expire=0, expireAccess=0, expireMaxSize = 0, expireStoreSize=0;
long[] expireHeads=null, expireTails=null;
if(m.ondisk!=null) {
if (m.valueCreator != null) {
throw new IllegalArgumentException("ValueCreator can not be used together with ExpireOverflow.");
}
final Map ondisk = m.ondisk;
m.valueCreator = new Fun.Function1<Object, Object>() {
@Override
public Object run(Object key) {
return ondisk.get(key);
}
};
}
if(m.expire!=0 || m.expireAccess!=0 || m.expireMaxSize !=0 || m.expireStoreSize!=0){
expireTimeStart = catPut(name+".expireTimeStart",System.currentTimeMillis());
expire = catPut(name+".expire",m.expire);
expireAccess = catPut(name+".expireAccess",m.expireAccess);
expireMaxSize = catPut(name+".expireMaxSize",m.expireMaxSize);
expireStoreSize = catPut(name+".expireStoreSize",m.expireStoreSize);
//$DELAY$
expireHeads = new long[HTreeMap.SEG];
expireTails = new long[HTreeMap.SEG];
for(int i=0;i<HTreeMap.SEG;i++){
expireHeads[i] = m.engines[i].put(0L,Serializer.LONG);
expireTails[i] = m.engines[i].put(0L, Serializer.LONG);
}
catPut(name+".expireHeads",expireHeads);
catPut(name+".expireTails",expireTails);
}
//$DELAY$
long[] counterRecids = null;
if(m.counter){
counterRecids = new long[HTreeMap.SEG];
for(int i=0;i<HTreeMap.SEG;i++){
counterRecids[i] = m.engines[i].put(0L,Serializer.LONG);
}
}
if(m.keySerializer==null) {
m.keySerializer = getDefaultSerializer();
}
catPut(name+".keySerializer",serializableOrPlaceHolder(m.keySerializer));
if(m.valueSerializer==null) {
m.valueSerializer = getDefaultSerializer();
}
catPut(name+".valueSerializer",serializableOrPlaceHolder(m.valueSerializer));
HTreeMap<K,V> ret = new HTreeMap<K,V>(
m.engines,
m.closeEngine,
counterRecids==null? null : catPut(name + ".counterRecids", counterRecids),
catPut(name+".hashSalt",new SecureRandom().nextInt()),
catPut(name+".segmentRecids",HTreeMap.preallocateSegments(m.engines)),
(Serializer<K>)m.keySerializer,
(Serializer<V>)m.valueSerializer,
expireTimeStart,expire,expireAccess,expireMaxSize, expireStoreSize, expireHeads ,expireTails,
(Fun.Function1<V, K>) m.valueCreator,
m.executor,
m.executorPeriod,
m.executor!=executor,
consistencyLock.readLock());
//$DELAY$
catalog.put(name + ".type", "HashMap");
namedPut(name, ret);
//pump data if specified2
if(m.pumpSource!=null) {
Pump.fillHTreeMap(
ret,
m.pumpSource,
m.pumpKeyExtractor,
m.pumpValueExtractor,
m.pumpPresortBatchSize,
m.pumpIgnoreDuplicates,
getDefaultSerializer(),
m.executor);
}
if(m.ondisk!=null){
Bind.mapPutAfterDelete(ret,m.ondisk, m.ondiskOverwrite);
}
return ret;
}
protected Object serializableOrPlaceHolder(Object o) {
SerializerBase b = (SerializerBase)getDefaultSerializer();
if(o == null || b.isSerializable(o)){
if(!(o instanceof BTreeKeySerializer.BasicKeySerializer))
return o;
BTreeKeySerializer.BasicKeySerializer oo = (BTreeKeySerializer.BasicKeySerializer) o;
if(b.isSerializable(oo.serializer) && b.isSerializable(oo.comparator))
return o;
}
return Fun.PLACEHOLDER;
}
/**
* @deprecated method renamed, use {@link DB#hashSet(String)}
*/
synchronized public <K> Set<K> getHashSet(String name){
return hashSet(name);
}
/**
* Opens existing or creates new Hash Tree Set.
*
* @param name of the Set
* @return set
*/
synchronized public <K> Set<K> hashSet(String name){
return hashSet(name,null);
}
synchronized public <K> Set<K> hashSet(String name, Serializer<K> serializer){
checkNotClosed();
Set<K> ret = (Set<K>) getFromWeakCollection(name);
if(ret!=null) return ret;
String type = catGet(name + ".type", null);
//$DELAY$
if(type==null){
checkShouldCreate(name);
if(engine.isReadOnly()){
Engine e = new StoreHeap(true,1,0,false);
//$DELAY$
new DB(e).hashSet("a");
return namedPut(name,
new DB(new Engine.ReadOnlyWrapper(e)).hashSet("a"));
}
HTreeSetMaker m = hashSetCreate(name);
if(serializer!=null)
m = m.serializer(serializer);
return m.makeOrGet();
//$DELAY$
}
//check type
checkType(type, "HashSet");
Object keySer2 = catGet(name+".serializer");
if(serializer!=null){
if(keySer2!=Fun.PLACEHOLDER && keySer2!=serializer){
LOG.warning("Set '"+name+"' has serializer defined in Name Catalog, but other serializer was passed as constructor argument. Using one from constructor argument.");
}
keySer2 = serializer;
}
if(keySer2==Fun.PLACEHOLDER){
throw new DBException.UnknownSerializer("Set '"+name+"' has no serializer defined in Name Catalog nor constructor argument.");
}
//open existing map
ret = new HTreeMap<K, Object>(
HTreeMap.fillEngineArray(engine),
false,
(long[])catGet(name+".counterRecids"),
(Integer)catGet(name+".hashSalt"),
(long[])catGet(name+".segmentRecids"),
(Serializer)keySer2,
null,
catGet(name+".expireTimeStart",0L),
catGet(name+".expire",0L),
catGet(name+".expireAccess",0L),
catGet(name+".expireMaxSize",0L),
catGet(name+".expireStoreSize",0L),
(long[])catGet(name+".expireHeads",null),
(long[])catGet(name+".expireTails",null),
null,
executor,
CC.DEFAULT_HTREEMAP_EXECUTOR_PERIOD,
false,
consistencyLock.readLock()
).keySet();
//$DELAY$
namedPut(name, ret);
//$DELAY$
return ret;
}
/**
* @deprecated method renamed, use {@link DB#hashSetCreate(String)}
*/
synchronized public HTreeSetMaker createHashSet(String name){
return hashSetCreate(name);
}
/**
* Creates new HashSet
*
* @param name of set to create
*/
synchronized public HTreeSetMaker hashSetCreate(String name){
return new HTreeSetMaker(name);
}
synchronized protected <K> Set<K> hashSetCreate(HTreeSetMaker m){
String name = m.name;
checkNameNotExists(name);
long expireTimeStart=0, expire=0, expireAccess=0, expireMaxSize = 0, expireStoreSize = 0;
long[] expireHeads=null, expireTails=null;
if(m.expire!=0 || m.expireAccess!=0 || m.expireMaxSize !=0){
expireTimeStart = catPut(name+".expireTimeStart",System.currentTimeMillis());
expire = catPut(name+".expire",m.expire);
expireAccess = catPut(name+".expireAccess",m.expireAccess);
expireMaxSize = catPut(name+".expireMaxSize",m.expireMaxSize);
expireStoreSize = catPut(name+".expireStoreSize",m.expireStoreSize);
expireHeads = new long[HTreeMap.SEG];
//$DELAY$
expireTails = new long[HTreeMap.SEG];
for(int i=0;i<HTreeMap.SEG;i++){
expireHeads[i] = engine.put(0L,Serializer.LONG);
expireTails[i] = engine.put(0L,Serializer.LONG);
}
catPut(name+".expireHeads",expireHeads);
catPut(name+".expireTails",expireTails);
}
//$DELAY$
Engine[] engines = HTreeMap.fillEngineArray(engine);
long[] counterRecids = null;
if(m.counter){
counterRecids = new long[HTreeMap.SEG];
for(int i=0;i<HTreeMap.SEG;i++){
counterRecids[i] = engines[i].put(0L,Serializer.LONG);
}
}
if(m.serializer==null) {
m.serializer = getDefaultSerializer();
}
catPut(name+".serializer",serializableOrPlaceHolder(m.serializer));
HTreeMap<K,Object> ret = new HTreeMap<K,Object>(
engines,
m.closeEngine,
counterRecids == null ? null : catPut(name + ".counterRecids", counterRecids),
catPut(name+".hashSalt", new SecureRandom().nextInt()), //TODO investigate if hashSalt actually prevents collision attack
catPut(name+".segmentRecids",HTreeMap.preallocateSegments(engines)),
(Serializer)m.serializer,
null,
expireTimeStart,expire,expireAccess,expireMaxSize, expireStoreSize, expireHeads ,expireTails,