/
OLocalHashTable.java
executable file
·2200 lines (1747 loc) · 80.5 KB
/
OLocalHashTable.java
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 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * 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.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.index.hashindex.local;
import com.orientechnologies.common.comparator.ODefaultComparator;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.index.OIndexException;
import com.orientechnologies.orient.core.index.hashindex.local.cache.OCacheEntry;
import com.orientechnologies.orient.core.index.hashindex.local.cache.ODiskCache;
import com.orientechnologies.orient.core.index.sbtree.local.OSBTreeException;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializerFactory;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OStorageTransaction;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurableComponent;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
/**
* Implementation of hash index which is based on <a href="http://en.wikipedia.org/wiki/Extendible_hashing">extendible hashing
* algorithm</a>. The directory for extindible hashing is implemented in
* {@link com.orientechnologies.orient.core.index.hashindex.local.OHashTableDirectory} class. Directory is not implemented according
* to classic algorithm because of its big memory consumption in case of non-uniform data distribution instead it is implemented
* according too "Multilevel Extendible Hashing Sven Helmer, Thomas Neumann, Guido Moerkotte April 17, 2002". Which has much less
* memory consumption in case of nonuniform data distribution.
*
* Index itself uses so called "muiltilevel schema" when first level contains 256 buckets, when bucket is split it is put at the
* end of other file which represents second level. So if data which are put has distribution close to uniform (this index was
* designed to be use as rid index for DHT storage) buckets split will be preformed in append only manner to speed up index write
* speed.
*
* So hash index bucket itself has following structure:
* <ol>
* <li>Bucket depth - 1 byte.</li>
* <li>Bucket's size - amount of entities (key, value) in one bucket, 4 bytes</li>
* <li>Page indexes of parents of this bucket, page indexes of buckets split of which created current bucket - 64*8 bytes.</li>
* <li>Offsets of entities stored in this bucket relatively to it's beginning. It is array of int values of undefined size.</li>
* <li>Entities itself</li>
* </ol>
*
* So if 1-st and 2-nd fields are clear. We should discuss the last ones.
*
*
* Entities in bucket are sorted by key's hash code so each entity has following storage format in bucket: key's hash code (8
* bytes), key, value. Because entities are stored in sorted order it means that every time when we insert new entity old ones
* should be moved.
*
* There are 2 reasons why it is bad:
* <ol>
* <li>It will generate write ahead log of enormous size.</li>
* <li>The more amount of memory is affected in operation the less speed we will have. In worst case 60 kb of memory should be
* moved.</li>
* </ol>
*
* To avoid disadvantages listed above entries ara appended to the end of bucket, but their offsets are stored at the beginning of
* bucket. Offsets are stored in sorted order (ordered by hash code of entity's key) so we need to move only small amount of memory
* to store entities in sorted order.
*
* About indexes of parents of current bucket. When item is removed from bucket we check space which is needed to store all entities
* of this bucket, it's buddy bucket (bucket which was also created from parent bucket during split) and if space of single bucket
* is enough to save all entities from both buckets we remove these buckets and put all content in parent bucket. That is why we
* need indexes of parents of current bucket.
*
* Also hash index has special file of one page long which contains information about state of each level of buckets in index. This
* information is stored as array index of which equals to file level. All array item has following structure:
* <ol>
* <li>Is level removed (in case all buckets are empty or level was not created yet) - 1 byte</li>
* <li>File's level id - 8 bytes</li>
* <li>Amount of buckets in given level - 8 bytes.</li>
* <li>Index of page of first removed bucket (not splitted but removed) - 8 bytes</li>
* </ol>
*
*
* @author Andrey Lomakin
* @since 12.03.13
*/
public class OLocalHashTable<K, V> extends ODurableComponent {
private static final double MERGE_THRESHOLD = 0.2;
private static final long HASH_CODE_MIN_VALUE = 0;
private static final long HASH_CODE_MAX_VALUE = 0xFFFFFFFFFFFFFFFFL;
private final String metadataConfigurationFileExtension;
private final String treeStateFileExtension;
private final String bucketFileExtension;
public static final int HASH_CODE_SIZE = 64;
public static final int MAX_LEVEL_DEPTH = 8;
public static final int MAX_LEVEL_SIZE = 1 << MAX_LEVEL_DEPTH;
public static final int LEVEL_MASK = Integer.MAX_VALUE >>> (31 - MAX_LEVEL_DEPTH);
private OAbstractPaginatedStorage storage;
private String name;
private ODiskCache diskCache;
private final OHashFunction<K> keyHashFunction;
private OBinarySerializer<K> keySerializer;
private OBinarySerializer<V> valueSerializer;
private OType[] keyTypes;
private final KeyHashCodeComparator<K> comparator;
private boolean nullKeyIsSupported;
private long nullBucketFileId = -1;
private final String nullBucketFileExtension;
private long fileStateId;
private OCacheEntry hashStateEntry;
private OHashTableDirectory directory;
private final boolean durableInNonTxMode;
private final ODurablePage.TrackMode trackMode;
public OLocalHashTable(String metadataConfigurationFileExtension, String treeStateFileExtension, String bucketFileExtension,
String nullBucketFileExtension, OHashFunction<K> keyHashFunction, boolean durableInNonTxMode, ODurablePage.TrackMode trackMode) {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
this.metadataConfigurationFileExtension = metadataConfigurationFileExtension;
this.treeStateFileExtension = treeStateFileExtension;
this.bucketFileExtension = bucketFileExtension;
this.keyHashFunction = keyHashFunction;
this.nullBucketFileExtension = nullBucketFileExtension;
this.durableInNonTxMode = durableInNonTxMode;
this.comparator = new KeyHashCodeComparator<K>(this.keyHashFunction);
if (trackMode == null)
this.trackMode = ODurablePage.TrackMode.valueOf(OGlobalConfiguration.INDEX_TX_MODE.getValueAsString().toUpperCase());
else
this.trackMode = trackMode;
}
public void create(String name, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer, OType[] keyTypes,
OAbstractPaginatedStorage storageLocal, boolean nullKeyIsSupported) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.keyTypes = keyTypes;
this.nullKeyIsSupported = nullKeyIsSupported;
this.diskCache = storage.getDiskCache();
if (this.diskCache == null)
throw new IllegalStateException("Disk cache was not initialized on storage level");
this.name = name;
init(storage);
this.directory = new OHashTableDirectory(treeStateFileExtension, name, durableInNonTxMode, storage);
startAtomicOperation();
try {
fileStateId = diskCache.openFile(name + metadataConfigurationFileExtension);
logFileCreation(name + metadataConfigurationFileExtension, fileStateId);
directory.create();
hashStateEntry = diskCache.allocateNewPage(fileStateId);
diskCache.pinPage(hashStateEntry);
hashStateEntry.acquireExclusiveLock();
try {
OHashIndexFileLevelMetadataPage page = new OHashIndexFileLevelMetadataPage(hashStateEntry, getTrackMode(), true);
createFileMetadata(0, page);
hashStateEntry.markDirty();
logPageChanges(page, hashStateEntry.getFileId(), hashStateEntry.getPageIndex(), true);
} finally {
hashStateEntry.releaseExclusiveLock();
diskCache.release(hashStateEntry);
}
setKeySerializer(keySerializer);
setValueSerializer(valueSerializer);
initHashTreeState();
if (nullKeyIsSupported) {
nullBucketFileId = diskCache.openFile(name + nullBucketFileExtension);
logFileCreation(name + nullBucketFileExtension, nullBucketFileId);
}
endAtomicOperation(false);
} catch (IOException e) {
endAtomicOperation(true);
throw e;
} catch (Throwable e) {
endAtomicOperation(true);
throw new OStorageException(null, e);
}
} catch (IOException e) {
throw new OIndexException("Error during local hash table creation.", e);
} finally {
releaseExclusiveLock();
}
}
@Override
protected ODurablePage.TrackMode getTrackMode() {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return ODurablePage.TrackMode.NONE;
final ODurablePage.TrackMode trackMode = super.getTrackMode();
if (!trackMode.equals(ODurablePage.TrackMode.NONE))
return this.trackMode;
return trackMode;
}
@Override
protected void endAtomicOperation(boolean rollback) throws IOException {
if (storage.getStorageTransaction() == null && !durableInNonTxMode)
return;
super.endAtomicOperation(rollback);
}
@Override
protected void startAtomicOperation() throws IOException {
if (storage.getStorageTransaction() == null && !durableInNonTxMode)
return;
super.startAtomicOperation();
}
@Override
protected void logFileCreation(String fileName, long fileId) throws IOException {
if (storage.getStorageTransaction() == null && !durableInNonTxMode)
return;
super.logFileCreation(fileName, fileId);
}
@Override
protected void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage) throws IOException {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return;
super.logPageChanges(localPage, fileId, pageIndex, isNewPage);
}
public OBinarySerializer<K> getKeySerializer() {
acquireSharedLock();
try {
return keySerializer;
} finally {
releaseSharedLock();
}
}
public void setKeySerializer(OBinarySerializer<K> keySerializer) {
acquireExclusiveLock();
try {
startAtomicOperation();
this.keySerializer = keySerializer;
diskCache.loadPinnedPage(hashStateEntry);
hashStateEntry.acquireExclusiveLock();
try {
OHashIndexFileLevelMetadataPage metadataPage = new OHashIndexFileLevelMetadataPage(hashStateEntry, getTrackMode(), false);
metadataPage.setKeySerializerId(keySerializer.getId());
hashStateEntry.markDirty();
logPageChanges(metadataPage, hashStateEntry.getFileId(), hashStateEntry.getPageIndex(), false);
} finally {
hashStateEntry.releaseExclusiveLock();
diskCache.release(hashStateEntry);
}
endAtomicOperation(false);
} catch (IOException e) {
rollback();
throw new OIndexException("Can not set serializer for index keys", e);
} catch (Throwable e) {
rollback();
throw new OStorageException(null, e);
} finally {
releaseExclusiveLock();
}
}
private void rollback() {
try {
endAtomicOperation(true);
} catch (IOException ioe) {
throw new OIndexException("Error during operation roolback", ioe);
}
}
public OBinarySerializer<V> getValueSerializer() {
acquireSharedLock();
try {
return valueSerializer;
} finally {
releaseSharedLock();
}
}
public void setValueSerializer(OBinarySerializer<V> valueSerializer) {
acquireExclusiveLock();
try {
startAtomicOperation();
this.valueSerializer = valueSerializer;
diskCache.loadPinnedPage(hashStateEntry);
hashStateEntry.acquireExclusiveLock();
try {
OHashIndexFileLevelMetadataPage metadataPage = new OHashIndexFileLevelMetadataPage(hashStateEntry, getTrackMode(), false);
metadataPage.setValueSerializerId(valueSerializer.getId());
hashStateEntry.markDirty();
logPageChanges(metadataPage, hashStateEntry.getFileId(), hashStateEntry.getPageIndex(), false);
} finally {
hashStateEntry.releaseExclusiveLock();
diskCache.release(hashStateEntry);
}
endAtomicOperation(false);
} catch (IOException e) {
rollback();
throw new OIndexException("Can not set serializer for index values", e);
} catch (Throwable e) {
rollback();
throw new OStorageException(null, e);
} finally {
releaseExclusiveLock();
}
}
private void createFileMetadata(int fileLevel, OHashIndexFileLevelMetadataPage page) throws IOException {
final String fileName = name + fileLevel + bucketFileExtension;
final long fileId = diskCache.openFile(fileName);
logFileCreation(fileName, fileId);
page.setFileMetadata(fileLevel, fileId, 0, -1);
}
public V get(K key) {
acquireSharedLock();
try {
checkNullSupport(key);
if (key == null) {
if (diskCache.getFilledUpTo(nullBucketFileId) == 0)
return null;
V result = null;
OCacheEntry cacheEntry = diskCache.load(nullBucketFileId, 0, false);
try {
ONullBucket<V> nullBucket = new ONullBucket<V>(cacheEntry, ODurablePage.TrackMode.NONE, valueSerializer, false);
result = nullBucket.getValue();
} finally {
diskCache.release(cacheEntry);
}
return result;
} else {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final long hashCode = keyHashFunction.hashCode(key);
BucketPath bucketPath = getBucket(hashCode);
final long bucketPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
if (bucketPointer == 0)
return null;
long pageIndex = getPageIndex(bucketPointer);
int fileLevel = getFileLevel(bucketPointer);
OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
try {
final OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
ODurablePage.TrackMode.NONE);
OHashIndexBucket.Entry<K, V> entry = bucket.find(key, hashCode);
if (entry == null)
return null;
return entry.value;
} finally {
diskCache.release(cacheEntry);
}
}
} catch (IOException e) {
throw new OIndexException("Exception during index value retrieval", e);
} finally {
releaseSharedLock();
}
}
public void put(K key, V value) {
acquireExclusiveLock();
try {
startAtomicOperation();
checkNullSupport(key);
key = keySerializer.preprocess(key, (Object[]) keyTypes);
doPut(key, value);
endAtomicOperation(false);
} catch (IOException e) {
rollback();
throw new OIndexException("Error during index update", e);
} catch (Throwable e) {
rollback();
throw new OStorageException(null, e);
} finally {
releaseExclusiveLock();
}
}
public V remove(K key) {
acquireExclusiveLock();
try {
startAtomicOperation();
checkNullSupport(key);
int sizeDiff = 0;
if (key != null) {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final long hashCode = keyHashFunction.hashCode(key);
final BucketPath nodePath = getBucket(hashCode);
final long bucketPointer = directory.getNodePointer(nodePath.nodeIndex, nodePath.itemIndex + nodePath.hashMapOffset);
final long pageIndex = getPageIndex(bucketPointer);
final int fileLevel = getFileLevel(bucketPointer);
final V removed;
final OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
cacheEntry.acquireExclusiveLock();
try {
final OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
getTrackMode());
final int positionIndex = bucket.getIndex(hashCode, key);
if (positionIndex < 0) {
endAtomicOperation(false);
return null;
}
removed = bucket.deleteEntry(positionIndex).value;
sizeDiff--;
mergeBucketsAfterDeletion(nodePath, bucket);
cacheEntry.markDirty();
logPageChanges(bucket, cacheEntry.getFileId(), cacheEntry.getPageIndex(), false);
} finally {
cacheEntry.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
if (nodePath.parent != null) {
final int hashMapSize = 1 << nodePath.nodeLocalDepth;
final boolean allMapsContainSameBucket = checkAllMapsContainSameBucket(directory.getNode(nodePath.nodeIndex), hashMapSize);
if (allMapsContainSameBucket)
mergeNodeToParent(nodePath);
}
changeSize(sizeDiff);
endAtomicOperation(false);
return removed;
} else {
if (diskCache.getFilledUpTo(nullBucketFileId) == 0)
return null;
V removed = null;
OCacheEntry cacheEntry = diskCache.load(nullBucketFileId, 0, false);
if (cacheEntry == null)
cacheEntry = diskCache.allocateNewPage(nullBucketFileId);
cacheEntry.acquireExclusiveLock();
try {
final ONullBucket<V> nullBucket = new ONullBucket<V>(cacheEntry, getTrackMode(), valueSerializer, false);
removed = nullBucket.getValue();
if (removed != null) {
nullBucket.removeValue();
sizeDiff--;
cacheEntry.markDirty();
logPageChanges(nullBucket, cacheEntry.getFileId(), cacheEntry.getPageIndex(), false);
}
} finally {
cacheEntry.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
changeSize(sizeDiff);
endAtomicOperation(false);
return removed;
}
} catch (IOException e) {
rollback();
throw new OIndexException("Error during index removal", e);
} catch (Throwable e) {
rollback();
throw new OStorageException(null, e);
} finally {
releaseExclusiveLock();
}
}
private void changeSize(int sizeDiff) throws IOException {
if (sizeDiff != 0) {
diskCache.loadPinnedPage(hashStateEntry);
hashStateEntry.acquireExclusiveLock();
try {
OHashIndexFileLevelMetadataPage page = new OHashIndexFileLevelMetadataPage(hashStateEntry, getTrackMode(), false);
page.setRecordsCount(page.getRecordsCount() + sizeDiff);
hashStateEntry.markDirty();
logPageChanges(page, hashStateEntry.getFileId(), hashStateEntry.getPageIndex(), false);
} finally {
hashStateEntry.releaseExclusiveLock();
diskCache.release(hashStateEntry);
}
}
}
public void clear() {
acquireExclusiveLock();
try {
startAtomicOperation();
diskCache.loadPinnedPage(hashStateEntry);
hashStateEntry.acquireExclusiveLock();
try {
OHashIndexFileLevelMetadataPage page = new OHashIndexFileLevelMetadataPage(hashStateEntry, getTrackMode(), false);
for (int i = 0; i < HASH_CODE_SIZE; i++) {
if (!page.isRemoved(i)) {
diskCache.truncateFile(page.getFileId(i));
page.setBucketsCount(i, 0);
page.setTombstoneIndex(i, -1);
}
}
hashStateEntry.markDirty();
logPageChanges(page, hashStateEntry.getFileId(), hashStateEntry.getPageIndex(), false);
} finally {
hashStateEntry.releaseExclusiveLock();
diskCache.release(hashStateEntry);
}
if (nullKeyIsSupported)
diskCache.truncateFile(nullBucketFileId);
initHashTreeState();
endAtomicOperation(false);
} catch (IOException e) {
rollback();
throw new OIndexException("Error during hash table clear", e);
} catch (Throwable e) {
rollback();
throw new OSBTreeException(null, e);
} finally {
releaseExclusiveLock();
}
}
public OHashIndexBucket.Entry<K, V>[] higherEntries(K key) {
return higherEntries(key, -1);
}
public OHashIndexBucket.Entry<K, V>[] higherEntries(K key, int limit) {
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final long hashCode = keyHashFunction.hashCode(key);
BucketPath bucketPath = getBucket(hashCode);
long bucketPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
int fileLevel = getFileLevel(bucketPointer);
long pageIndex = getPageIndex(bucketPointer);
OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
try {
OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
ODurablePage.TrackMode.NONE);
while (bucket.size() == 0 || comparator.compare(bucket.getKey(bucket.size() - 1), key) <= 0) {
bucketPath = nextBucketToFind(bucketPath, bucket.getDepth());
if (bucketPath == null)
return new OHashIndexBucket.Entry[0];
diskCache.release(cacheEntry);
final long nextPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
fileLevel = getFileLevel(nextPointer);
pageIndex = getPageIndex(nextPointer);
cacheEntry = loadPageEntry(pageIndex, fileLevel);
bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes, ODurablePage.TrackMode.NONE);
}
final int index = bucket.getIndex(hashCode, key);
final int startIndex;
if (index >= 0)
startIndex = index + 1;
else
startIndex = -index - 1;
final int endIndex;
if (limit <= 0)
endIndex = bucket.size();
else
endIndex = Math.min(bucket.size(), startIndex + limit);
return convertBucketToEntries(bucket, startIndex, endIndex);
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException ioe) {
throw new OIndexException("Exception during data retrieval", ioe);
} finally {
releaseSharedLock();
}
}
public void load(String name, OType[] keyTypes, OAbstractPaginatedStorage storageLocal, boolean nullKeyIsSupported) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.keyTypes = keyTypes;
this.nullKeyIsSupported = nullKeyIsSupported;
diskCache = storage.getDiskCache();
this.name = name;
init(storage);
fileStateId = diskCache.openFile(name + metadataConfigurationFileExtension);
hashStateEntry = diskCache.load(fileStateId, 0, true);
directory = new OHashTableDirectory(treeStateFileExtension, name, durableInNonTxMode, storage);
directory.open();
diskCache.pinPage(hashStateEntry);
try {
OHashIndexFileLevelMetadataPage page = new OHashIndexFileLevelMetadataPage(hashStateEntry, ODurablePage.TrackMode.NONE,
false);
keySerializer = (OBinarySerializer<K>) OBinarySerializerFactory.getInstance()
.getObjectSerializer(page.getKeySerializerId());
valueSerializer = (OBinarySerializer<V>) OBinarySerializerFactory.getInstance().getObjectSerializer(
page.getValueSerializerId());
for (int i = 0; i < HASH_CODE_SIZE; i++)
if (!page.isRemoved(i))
diskCache.openFile(page.getFileId(i));
} finally {
diskCache.release(hashStateEntry);
}
if (nullKeyIsSupported)
nullBucketFileId = diskCache.openFile(name + nullBucketFileExtension);
} catch (IOException e) {
throw new OIndexException("Exception during hash table loading", e);
} finally {
releaseExclusiveLock();
}
}
public void deleteWithoutLoad(String name, OAbstractPaginatedStorage storageLocal) {
acquireExclusiveLock();
try {
storage = storageLocal;
final ODiskCache diskCache = storage.getDiskCache();
fileStateId = diskCache.openFile(name + metadataConfigurationFileExtension);
hashStateEntry = diskCache.load(fileStateId, 0, true);
assert hashStateEntry != null;
try {
OHashIndexFileLevelMetadataPage metadataPage = new OHashIndexFileLevelMetadataPage(hashStateEntry,
ODurablePage.TrackMode.NONE, false);
for (int i = 0; i < HASH_CODE_SIZE; i++) {
if (!metadataPage.isRemoved(i)) {
diskCache.openFile(metadataPage.getFileId(i));
diskCache.deleteFile(metadataPage.getFileId(i));
}
}
} finally {
diskCache.release(hashStateEntry);
}
diskCache.deleteFile(fileStateId);
directory = new OHashTableDirectory(treeStateFileExtension, name, durableInNonTxMode, storage);
directory.deleteWithoutOpen();
final long nullBucketId = diskCache.openFile(name + nullBucketFileExtension);
diskCache.deleteFile(nullBucketId);
} catch (IOException ioe) {
throw new OIndexException("Can not delete hash table with name " + name, ioe);
} finally {
releaseExclusiveLock();
}
}
private OHashIndexBucket.Entry<K, V>[] convertBucketToEntries(final OHashIndexBucket<K, V> bucket, int startIndex, int endIndex) {
final OHashIndexBucket.Entry<K, V>[] entries = new OHashIndexBucket.Entry[endIndex - startIndex];
final Iterator<OHashIndexBucket.Entry<K, V>> iterator = bucket.iterator(startIndex);
for (int i = 0, k = startIndex; k < endIndex; i++, k++)
entries[i] = iterator.next();
return entries;
}
private BucketPath nextBucketToFind(final BucketPath bucketPath, int bucketDepth) throws IOException {
int offset = bucketPath.nodeGlobalDepth - bucketDepth;
BucketPath currentNode = bucketPath;
int nodeLocalDepth = directory.getNodeLocalDepth(bucketPath.nodeIndex);
assert directory.getNodeLocalDepth(bucketPath.nodeIndex) == bucketPath.nodeLocalDepth;
while (offset > 0) {
offset -= nodeLocalDepth;
if (offset > 0) {
currentNode = bucketPath.parent;
nodeLocalDepth = currentNode.nodeLocalDepth;
assert directory.getNodeLocalDepth(currentNode.nodeIndex) == currentNode.nodeLocalDepth;
}
}
final int diff = bucketDepth - (currentNode.nodeGlobalDepth - nodeLocalDepth);
final int interval = (1 << (nodeLocalDepth - diff));
final int firstStartIndex = currentNode.itemIndex & ((LEVEL_MASK << (nodeLocalDepth - diff)) & LEVEL_MASK);
final BucketPath bucketPathToFind;
final int globalIndex = firstStartIndex + interval + currentNode.hashMapOffset;
if (globalIndex >= MAX_LEVEL_SIZE)
bucketPathToFind = nextLevelUp(currentNode);
else {
final int hashMapSize = 1 << currentNode.nodeLocalDepth;
final int hashMapOffset = globalIndex / hashMapSize * hashMapSize;
final int startIndex = globalIndex - hashMapOffset;
bucketPathToFind = new BucketPath(currentNode.parent, hashMapOffset, startIndex, currentNode.nodeIndex,
currentNode.nodeLocalDepth, currentNode.nodeGlobalDepth);
}
return nextNonEmptyNode(bucketPathToFind);
}
private BucketPath nextNonEmptyNode(BucketPath bucketPath) throws IOException {
nextBucketLoop: while (bucketPath != null) {
final long[] node = directory.getNode(bucketPath.nodeIndex);
final int startIndex = bucketPath.itemIndex + bucketPath.hashMapOffset;
final int endIndex = MAX_LEVEL_SIZE;
for (int i = startIndex; i < endIndex; i++) {
final long position = node[i];
if (position > 0) {
final int hashMapSize = 1 << bucketPath.nodeLocalDepth;
final int hashMapOffset = (i / hashMapSize) * hashMapSize;
final int itemIndex = i - hashMapOffset;
return new BucketPath(bucketPath.parent, hashMapOffset, itemIndex, bucketPath.nodeIndex, bucketPath.nodeLocalDepth,
bucketPath.nodeGlobalDepth);
}
if (position < 0) {
final int childNodeIndex = (int) ((position & Long.MAX_VALUE) >> 8);
final int childItemOffset = (int) position & 0xFF;
final BucketPath parent = new BucketPath(bucketPath.parent, 0, i, bucketPath.nodeIndex, bucketPath.nodeLocalDepth,
bucketPath.nodeGlobalDepth);
final int childLocalDepth = directory.getNodeLocalDepth(childNodeIndex);
bucketPath = new BucketPath(parent, childItemOffset, 0, childNodeIndex, childLocalDepth, bucketPath.nodeGlobalDepth
+ childLocalDepth);
continue nextBucketLoop;
}
}
bucketPath = nextLevelUp(bucketPath);
}
return null;
}
private BucketPath nextLevelUp(BucketPath bucketPath) throws IOException {
if (bucketPath.parent == null)
return null;
final int nodeLocalDepth = bucketPath.nodeLocalDepth;
assert directory.getNodeLocalDepth(bucketPath.nodeIndex) == bucketPath.nodeLocalDepth;
final int pointersSize = 1 << (MAX_LEVEL_DEPTH - nodeLocalDepth);
final BucketPath parent = bucketPath.parent;
if (parent.itemIndex < MAX_LEVEL_SIZE / 2) {
final int nextParentIndex = (parent.itemIndex / pointersSize + 1) * pointersSize;
return new BucketPath(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeLocalDepth, parent.nodeGlobalDepth);
}
final int nextParentIndex = ((parent.itemIndex - MAX_LEVEL_SIZE / 2) / pointersSize + 1) * pointersSize + MAX_LEVEL_SIZE / 2;
if (nextParentIndex < MAX_LEVEL_SIZE)
return new BucketPath(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeLocalDepth, parent.nodeGlobalDepth);
return nextLevelUp(new BucketPath(parent.parent, 0, MAX_LEVEL_SIZE - 1, parent.nodeIndex, parent.nodeLocalDepth,
parent.nodeGlobalDepth));
}
public OHashIndexBucket.Entry<K, V>[] ceilingEntries(K key) {
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final long hashCode = keyHashFunction.hashCode(key);
BucketPath bucketPath = getBucket(hashCode);
long bucketPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
int fileLevel = getFileLevel(bucketPointer);
long pageIndex = getPageIndex(bucketPointer);
OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
try {
OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
ODurablePage.TrackMode.NONE);
while (bucket.size() == 0) {
bucketPath = nextBucketToFind(bucketPath, bucket.getDepth());
if (bucketPath == null)
return new OHashIndexBucket.Entry[0];
diskCache.release(cacheEntry);
final long nextPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
fileLevel = getFileLevel(nextPointer);
pageIndex = getPageIndex(nextPointer);
cacheEntry = loadPageEntry(pageIndex, fileLevel);
bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes, ODurablePage.TrackMode.NONE);
}
final int index = bucket.getIndex(hashCode, key);
final int startIndex;
if (index >= 0)
startIndex = index;
else
startIndex = -index - 1;
final int endIndex = bucket.size();
return convertBucketToEntries(bucket, startIndex, endIndex);
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException ioe) {
throw new OIndexException("Error during data retrieval", ioe);
} finally {
releaseSharedLock();
}
}
public OHashIndexBucket.Entry<K, V> firstEntry() {
acquireSharedLock();
try {
BucketPath bucketPath = getBucket(HASH_CODE_MIN_VALUE);
long bucketPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex);
int fileLevel = getFileLevel(bucketPointer);
long pageIndex = getPageIndex(bucketPointer);
OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
try {
OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
ODurablePage.TrackMode.NONE);
while (bucket.size() == 0) {
bucketPath = nextBucketToFind(bucketPath, bucket.getDepth());
if (bucketPath == null)
return null;
diskCache.release(cacheEntry);
final long nextPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
fileLevel = getFileLevel(nextPointer);
pageIndex = getPageIndex(nextPointer);
cacheEntry = loadPageEntry(pageIndex, fileLevel);
bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes, ODurablePage.TrackMode.NONE);
}
return bucket.getEntry(0);
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException ioe) {
throw new OIndexException("Exception during data read", ioe);
} finally {
releaseSharedLock();
}
}
public OHashIndexBucket.Entry<K, V> lastEntry() {
acquireSharedLock();
try {
BucketPath bucketPath = getBucket(HASH_CODE_MAX_VALUE);
long bucketPointer = directory.getNodePointer(bucketPath.nodeIndex, bucketPath.itemIndex + bucketPath.hashMapOffset);
int fileLevel = getFileLevel(bucketPointer);
long pageIndex = getPageIndex(bucketPointer);
OCacheEntry cacheEntry = loadPageEntry(pageIndex, fileLevel);
try {
OHashIndexBucket<K, V> bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes,
ODurablePage.TrackMode.NONE);
while (bucket.size() == 0) {
final BucketPath prevBucketPath = prevBucketToFind(bucketPath, bucket.getDepth());
if (prevBucketPath == null)
return null;
diskCache.release(cacheEntry);
final long prevPointer = directory.getNodePointer(prevBucketPath.nodeIndex, prevBucketPath.itemIndex
+ prevBucketPath.hashMapOffset);
fileLevel = getFileLevel(prevPointer);
pageIndex = getPageIndex(prevPointer);
cacheEntry = loadPageEntry(pageIndex, fileLevel);
bucket = new OHashIndexBucket<K, V>(cacheEntry, keySerializer, valueSerializer, keyTypes, ODurablePage.TrackMode.NONE);
bucketPath = prevBucketPath;
}
return bucket.getEntry(bucket.size() - 1);
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException ioe) {
throw new OIndexException("Exception during data read", ioe);
} finally {
releaseSharedLock();
}
}
public OHashIndexBucket.Entry<K, V>[] lowerEntries(K key) {
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final long hashCode = keyHashFunction.hashCode(key);