forked from MinecraftTAS/BigArrayList
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBigArrayList.java
More file actions
1097 lines (909 loc) · 31.9 KB
/
BigArrayList.java
File metadata and controls
1097 lines (909 loc) · 31.9 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
/*
* BigArrayList
* Copyright (C) 2015 Douglas Selent
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dselent.bigarraylist;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* A BigArrayList acts the same way a regular {@link java.util.ArrayList} would for data sizes that cannot fit in memory all at once.
* This class can be used like an ArrayList with limited functionality. All the file I/O operations are managed automatically and internally.
* <p>
* The size and number of cache blocks to be stored in memory can be specified.
* <p>
* BigArrayList uses an internal ArrayList of ArrayLists (A list of cache blocks) to map data in memory to disk.
* The mapping is managed and maintained by the CacheMapping class.
* The File I/O uses Object input/output streams for classes that implement the serializable interface.
* An LRU cache policy is used to determine which block of data so swap out of memory.
* <p>
* A BigArrayList currently supports adding elements to the end of the list and setting/getting elements
* <p>
* Example code is below:
* <pre>
* {@code
* //Construct an instance of BigArrayList with 4 cache blocks of size 100,000 each
* //to store data in a folder called "memory" relative to the programs starting file path location
* BigArrayList<Long> arrayList = new BigArrayList<Long>("memory", 100000, 4);
*
* //Add elements to the list
* for(long i=0; i<1000000; i++)
* {
* arrayList.add(i);
* }
*
* //Set and get elements
* arrayList.set(10, 100L);
* long getElement = arrayList.get(10);
*
* //Clear data from disk when done
* arrayList.clearMemory();
* }
* </pre>
* <br/>
* @author Douglas Selent
*
* @param <E> Generic type
*/
public class BigArrayList<E extends Serializable> implements Iterable<E> {
/**
* The ArrayList of cache blocks.
* Each ArrayList corresponds to a cache block currently in memory
*/
private List<List<E>> arrayLists;
/**
* The SoftMapping object used to map the soft indices to the hard indices
*/
private final SoftMapping<E> softMapping;
/**
* The CacheMapping object used to map contents in memory to contents on disk
*/
private final CacheMapping<E> cacheMapping;
/**
* Size of the whole list including what is and is not currently in memory
*/
private long wholeListSize;
/**
* Default size of cache block = 1,000,000
*/
private static final int DEFAULT_BLOCK_SIZE = 1000000;
/**
* Default number of cache blocks = 2
*/
private static final int DEFAULT_CACHE_BLOCKS = 2;
/**
* The minimum size of a cache block = 5 elements
*/
private static final int MIN_CACHE_SIZE = 5;
/**
* The maximum size of a cache block = the integer limit of 2^31 - 1
*/
private static final int MAX_CACHE_SIZE = Integer.MAX_VALUE;
/**
* The minimum number of cache blocks = 2
*/
private static final int MIN_CACHE_BLOCKS = 2;
/**
* The maximum number of cache blocks = the integer limit of 2^31 - 1
*/
private static final int MAX_CACHE_BLOCKS = Integer.MAX_VALUE;
/**
* The size of the cache blocks
*/
private int blockSize;
/**
* The number of cache blocks
*/
private int cacheBlocks;
//all methods should check this and throw an exception if false
/**
* Whether or not the BigArrayList is still a live object.
* The contents of the BigArrayList must be manually cleared from disk using {@link #clearMemory()}.
* Doing so, will result in the BigArrayList object still existing in memory
* but it will be unusable since all the references point to content that has been deleted.
* In this case the BigArrayList is considered a dead object even though it is not technically considered dead by Java.
*/
private boolean liveObject;
/**
* Constructs a BigArrayList with default values for the number of cache blocks, size of each cache block, folder path, and serialization method.
*/
public BigArrayList() {
blockSize = DEFAULT_BLOCK_SIZE;
cacheBlocks = DEFAULT_CACHE_BLOCKS;
softMapping = new SoftMapping<E>();
cacheMapping = new CacheMapping<E>(this, blockSize, cacheBlocks);
arrayLists = new ArrayList<List<E>>();
for (int i = 0; i < cacheBlocks; i++) {
ArrayList<E> arrayList = new ArrayList<E>();
arrayList.ensureCapacity(blockSize);
arrayLists.add(arrayList);
}
wholeListSize = 0;
liveObject = true;
}
/**
* Constructs a BigArrayList with the specified folder path to use for swapping contents to and from disk. <br>
* Default values are used for the number of cache blocks, size of each cache block, and serialization method.
*
* @param folderPath The file path to write to
*/
public BigArrayList(String folderPath) {
blockSize = DEFAULT_BLOCK_SIZE;
cacheBlocks = DEFAULT_CACHE_BLOCKS;
softMapping = new SoftMapping<>();
cacheMapping = new CacheMapping<>(this, blockSize, cacheBlocks, folderPath);
arrayLists = new ArrayList<>();
for (int i = 0; i < cacheBlocks; i++) {
ArrayList<E> arrayList = new ArrayList<E>();
arrayList.ensureCapacity(blockSize);
arrayLists.add(arrayList);
}
wholeListSize = 0;
liveObject = true;
}
/**
* Constructs a BigArrayList with the specified block size and number of cache blocks to use. <br/>
* Default values are used for the folder path and serialization method.
*
* @param blockSize Size of each cache block
* @param cacheBlocks Number of cache blocks stored in memory at a given time
*/
public BigArrayList(int blockSize, int cacheBlocks) {
if (blockSize < MIN_CACHE_SIZE || blockSize > MAX_CACHE_SIZE) {
throw new IllegalArgumentException("Cache size is " + blockSize + " but must be >= " + MIN_CACHE_SIZE + " and <= " + MAX_CACHE_SIZE);
}
if (cacheBlocks < MIN_CACHE_BLOCKS || cacheBlocks > MAX_CACHE_BLOCKS) {
throw new IllegalArgumentException("Number of cache blocks is " + cacheBlocks + " but must be >= " + MIN_CACHE_BLOCKS + " and <= " + MAX_CACHE_BLOCKS);
}
this.blockSize = blockSize;
this.cacheBlocks = cacheBlocks;
softMapping = new SoftMapping<>();
cacheMapping = new CacheMapping<>(this, blockSize, cacheBlocks);
arrayLists = new ArrayList<>();
for (int i = 0; i < cacheBlocks; i++) {
ArrayList<E> arrayList = new ArrayList<>();
arrayList.ensureCapacity(blockSize);
arrayLists.add(arrayList);
}
wholeListSize = 0;
liveObject = true;
}
/**
* Constructs a BigArrayList with the size and number of cache blocks and the folder path to write to.
*
* @param blockSize cacheSize Size of each cache block
* @param cacheBlocks Number of cache blocks stored in memory at a given time
* @param folderPath The folder path to write to
*/
public BigArrayList(int blockSize, int cacheBlocks, String folderPath) {
if (blockSize < MIN_CACHE_SIZE || blockSize > MAX_CACHE_SIZE) {
throw new IllegalArgumentException("Cache size is " + blockSize + " but must be >= " + MIN_CACHE_SIZE + " and <= " + MAX_CACHE_SIZE);
}
if (cacheBlocks < MIN_CACHE_BLOCKS || cacheBlocks > MAX_CACHE_BLOCKS) {
throw new IllegalArgumentException("Number of cache blocks is " + cacheBlocks + " but must be >= " + MIN_CACHE_BLOCKS + " and <= " + MAX_CACHE_BLOCKS);
}
this.blockSize = blockSize;
this.cacheBlocks = cacheBlocks;
softMapping = new SoftMapping<>();
cacheMapping = new CacheMapping<>(this, blockSize, cacheBlocks, folderPath);
arrayLists = new ArrayList<>();
for (int i = 0; i < cacheBlocks; i++) {
ArrayList<E> arrayList = new ArrayList<>();
arrayList.ensureCapacity(blockSize);
arrayLists.add(arrayList);
}
wholeListSize = 0;
liveObject = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @return Returns the associated CacheMapping object
*/
protected CacheMapping<E> getCacheMapping() {
return cacheMapping;
}
/**
* @return Returns the number of blocks in memory at a time
*/
public int getNumberOfBlocks() {
return cacheBlocks;
}
/**
* @return Returns the block size
*/
public int getBlockSize() {
return blockSize;
}
/**
* @return Returns the number of used cache blocks based on the size of the list
*/
protected int getNumberOfUsedBlocks() {
long blockSizeLong = blockSize;
long usedBlocks = (long) Math.ceil(this.size() * 1.0 / blockSizeLong);
//safe cast, I really doubt there will ever be over 2^31 - 1 blocks
return (int) usedBlocks;
}
/**
* Returns the minimum of the number of used cache blocks based on the list size or the parameter size
*
* @param index A virtual size index
* @return The number of used cache blocks
*/
protected int getNumberOfUsedBlocks(long index) {
long blockSizeLong = blockSize;
long usedVirtualBlocks = (long) Math.ceil(index * 1.0 / blockSizeLong);
long usedRealBlocks = getNumberOfUsedBlocks();
long usedBlocks = Math.max(usedRealBlocks, usedVirtualBlocks);
//safe cast, I really doubt there will ever be over 2^31 - 1 blocks
return (int) usedBlocks;
}
/**
* @return Returns the file location of the memory storage
*/
public String getFilePath() {
return cacheMapping.getFileAccessor().getMemoryFilePath();
}
/**
* Sets the ArrayList at the given index
*
* @param index The index of the ArrayList/Cache block to set
* @param arrayList The new ArrayList/Cache block
*/
public void setList(int index, List<E> arrayList) {
arrayLists.set(index, arrayList);
}
/**
* Returns the ArrayList at the given index
*
* @param index The index of the ArrayList/Cache block to get
* @return The ArrayList/Cache block
*/
protected List<E> getList(int index) {
return arrayLists.get(index);
}
/**
* Used by the CacheMapping class for swapping caches.
* @param index The index of the cache block to clear data from
*/
protected void clearList(int index) {
arrayLists.get(index).clear();
}
/**
*
* @return The size of the BigArrayList
*/
public long size() {
return wholeListSize;
}
/**
* Returns the size of the ArrayList at the specified index
*
* @param index The index of the ArrayList/Cache block
* @return The size of ArrayList/Cache block
*/
protected int getArraySize(int index) {
return arrayLists.get(index).size();
}
/**
* Whether or no the object is live
* @return True if the object is live, false otherwise
*/
public boolean isLive() {
return liveObject;
}
/**
* Used to delete the memory file.
* The object should not be used anymore once this method is called
*
* @throws IOException For I/O error
*/
public void clearMemory() throws IOException {
cacheMapping.clearMemory();
liveObject = false;
}
/**
* Flushes all data in memory to disk
*/
public void flushMemory() {
cacheMapping.flushCache();
}
/**
* Sorts the BigArrayList. Note that the usage mimics Collections.sort() except that the sorted list is returned.
* The caller must set their list to equal the return value (similar to String concatenation), ex: sortedList = BigArrayList.sort(sortedList);
*
* @param unsortedList The list to be sorted
* @return The list in sorted order
* @throws IOException
*/
public static <T extends Comparable<? super T> & Serializable> BigArrayList<T> sort(BigArrayList<T> unsortedList) throws IOException {
return sort(unsortedList, Comparator.naturalOrder());
}
/**
* Sorts the BigArrayList. Note that the usage mimics Collections.sort() except that the sorted list is returned.
* The caller must set their list to equal the return value (similar to String concatenation), ex: sortedList = BigArrayList.sort(sortedList);
*
* @param unsortedList unsortedList The list to be sorted
* @param comparator How to compare the elements in the list
* @return The list in sorted order
* @throws IOException
*/
public static <T extends Serializable> BigArrayList<T> sort(BigArrayList<T> unsortedList, Comparator<? super T> comparator) throws IOException {
if (unsortedList.size() <= 1) {
return unsortedList;
} else {
unsortedList.purgeActionBuffer();
CacheMapping<T> unsortedCacheMapping = unsortedList.getCacheMapping();
int blockSize = unsortedList.getBlockSize();
int cacheBlocks = unsortedList.getNumberOfBlocks();
int usedCacheBlocks = unsortedList.getNumberOfUsedBlocks();
String filePath = unsortedList.getFilePath();
BigArrayList<T> sortedList = new BigArrayList<T>(blockSize, cacheBlocks, filePath);
for (int i = usedCacheBlocks - 1; i >= 0; i--) {
int cacheBlockSpot = -1;
if (!unsortedCacheMapping.isFileInCache(i)) {
unsortedCacheMapping.bringFileIntoCache(i);
}
cacheBlockSpot = unsortedCacheMapping.getCacheBlockSpot(i);
unsortedCacheMapping.setDirtyBit(cacheBlockSpot, true);
unsortedList.getList(cacheBlockSpot).sort(comparator);
}
if (usedCacheBlocks > 1) {
int currentRun = 0;
long totalRuns = 64 - Long.numberOfLeadingZeros(usedCacheBlocks - 1);
while (currentRun < totalRuns) {
sortedList = merge(unsortedList, comparator, currentRun);
unsortedList.clearMemory();
unsortedList = sortedList;
currentRun++;
}
} else {
sortedList = unsortedList;
}
return sortedList;
}
}
/**
* Internal function used to sort. This is the step to merge two sorted pieces together into a single sorted list.
*
* @param unsortedList The list
* @param comparator How to compare the elements
* @param currentRun What run step the merge is being used on. This is to determine what merge pieces to merge and their sizes
* @return The unsorted list with the sorted merged pieces.
*/
private static <T extends Serializable> BigArrayList<T> merge(BigArrayList<T> unsortedList, Comparator<? super T> comparator, int currentRun) {
int blockSize = unsortedList.getBlockSize();
int cacheBlocks = unsortedList.getNumberOfBlocks();
long usedCacheBlocksLong = unsortedList.getNumberOfUsedBlocks();
String filePath = unsortedList.getFilePath();
BigArrayList<T> sortedList = new BigArrayList<T>(blockSize, cacheBlocks, filePath);
int blockIncrement = ipow(2, currentRun);
for (long i = 0; i < usedCacheBlocksLong; i = i + blockIncrement + blockIncrement) {
long mergePiece1 = i;
long mergePiece2 = -1;
long mergePiece3 = -1;
long firstElementStart = mergePiece1 * blockSize;
long secondElementStart = -1;
long firstElementEnd = -1;
long secondElementEnd = -1;
long currentMergeElements = 0l;
long totalMergeElements = -1;
if (i + blockIncrement < usedCacheBlocksLong) {
mergePiece2 = i + blockIncrement;
mergePiece3 = i + blockIncrement + blockIncrement;
secondElementStart = mergePiece2 * blockSize;
firstElementEnd = secondElementStart;
if (unsortedList.size() >= mergePiece3 * blockSize) {
secondElementEnd = mergePiece3 * blockSize;
} else {
secondElementEnd = unsortedList.size();
}
totalMergeElements = secondElementEnd - firstElementStart;
} else {
if (unsortedList.size() >= (i + blockIncrement) * blockSize) {
firstElementEnd = (i + blockIncrement) * blockSize;
} else {
firstElementEnd = unsortedList.size();
}
totalMergeElements = firstElementEnd - firstElementStart;
}
long index1 = firstElementStart;
long index2 = secondElementStart;
if (mergePiece2 == -1 || mergePiece2 >= usedCacheBlocksLong) {
T element1 = unsortedList.get(index1);
while (currentMergeElements < totalMergeElements) {
sortedList.add(element1);
index1++;
if (index1 < firstElementEnd) {
element1 = unsortedList.get(index1);
}
currentMergeElements++;
}
} else {
T element1 = unsortedList.get(index1);
T element2 = unsortedList.get(index2);
while (currentMergeElements < totalMergeElements) {
if (index2 >= secondElementEnd) {
sortedList.add(element1);
index1++;
if (index1 < firstElementEnd) {
element1 = unsortedList.get(index1);
}
} else if (index1 >= firstElementEnd) {
sortedList.add(element2);
index2++;
if (index2 < secondElementEnd) {
element2 = unsortedList.get(index2);
}
} else {
if (comparator.compare(element1, element2) <= 0) {
sortedList.add(element1);
index1++;
if (index1 < firstElementEnd) {
element1 = unsortedList.get(index1);
}
} else {
sortedList.add(element2);
index2++;
if (index2 < secondElementEnd) {
element2 = unsortedList.get(index2);
}
}
}
currentMergeElements++;
}
}
}
return sortedList;
}
//skipping bound checks, trusting the caller to know that the result will not be greater an integer
/**
* Internal function used by sorting.
* modified function from http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int
*
* @param base Base number
* @param exp Exponent
* @return Ceiling of base^exp as a power of two
*/
private static int ipow(int base, int exp) {
int result = 1;
while (exp != 0) {
if ((exp & 1) == 1) {
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
/**
* Purges all actions in the queue
*/
private void purgeActionBuffer() {
if (softMapping.getBufferSize() > 0) {
long startIndex = softMapping.getShiftIndex(0);
//first index
int fileNumber = cacheMapping.getFileNumber(startIndex);
int nextFileNumber = fileNumber + 1;
long virtualSize = wholeListSize + softMapping.getLastShiftAmount();
int usedCacheBlocks = getNumberOfUsedBlocks(virtualSize);
int cacheBlockSpot = -1;
int nextCacheBlockSpot = -1;
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheBlockSpot = cacheMapping.bringFileIntoCache(fileNumber);
} else {
cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
cacheMapping.updateUsedList(cacheBlockSpot);
}
//assume there will be changes, this assumption is not always true?
cacheMapping.setDirtyBit(cacheBlockSpot, true);
if (!cacheMapping.isFileInCache(nextFileNumber)) {
nextCacheBlockSpot = cacheMapping.bringFileIntoCache(nextFileNumber);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
//SHOULD FIND MAX SHIFT TOO
while (nextFileNumber < usedCacheBlocks) {
List<E> cacheBlock = arrayLists.get(cacheBlockSpot);
List<E> nextCacheBlock = arrayLists.get(nextCacheBlockSpot);
//SHOULD FIND MAX SHIFT TOO
while (cacheBlock.size() < getBlockSize() && nextFileNumber < usedCacheBlocks) {
if (nextCacheBlock.size() > 0) {
cacheBlock.add(nextCacheBlock.remove(0));
cacheMapping.removeEntry(nextCacheBlockSpot);
cacheMapping.addEntry(cacheBlockSpot);
} else {
cacheMapping.updateUsedList(cacheBlockSpot);
nextFileNumber++;
//not reached end of blocks
if (nextFileNumber < usedCacheBlocks) {
//next file is not in cache
if (!cacheMapping.isFileInCache(nextFileNumber)) {
nextCacheBlockSpot = cacheMapping.bringFileIntoCache(nextFileNumber);
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
}
nextCacheBlock = arrayLists.get(nextCacheBlockSpot);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
}
}
fileNumber++;
if (fileNumber == nextFileNumber) {
nextFileNumber = fileNumber + 1;
}
//if not at end
if (nextFileNumber < usedCacheBlocks) {
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheBlockSpot = cacheMapping.bringFileIntoCache(fileNumber);
} else {
cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
cacheMapping.updateUsedList(cacheBlockSpot);
}
cacheMapping.setDirtyBit(cacheBlockSpot, true);
if (!cacheMapping.isFileInCache(nextFileNumber)) {
nextCacheBlockSpot = cacheMapping.bringFileIntoCache(nextFileNumber);
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
}
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
}
softMapping.removeAllShifts();
}
}
/**
* Purges action queue for all consecutive blocks in cache starting at startIndex
*
* @param startIndex The block index to start at
*/
private void purgeActionBufferInCache(long startIndex) {
if (softMapping.getBufferSize() > 0) {
boolean done = false;
//first index
int fileNumber = cacheMapping.getFileNumber(startIndex);
int nextFileNumber = fileNumber + 1;
long virtualSize = wholeListSize + softMapping.getLastShiftAmount();
int usedCacheBlocks = getNumberOfUsedBlocks(virtualSize);
int cacheBlockSpot = -1;
int nextCacheBlockSpot = -1;
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheBlockSpot = cacheMapping.bringFileIntoCache(fileNumber);
} else {
cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
}
//assume there will be changes, this assumption is not always true?
cacheMapping.setDirtyBit(cacheBlockSpot, true);
if (!cacheMapping.isFileInCache(nextFileNumber)) {
done = true;
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
long lastIndexInBlock = cacheMapping.getLastIndexInFile(fileNumber);
long lastIndexInNextBlock = cacheMapping.getLastIndexInFile(nextFileNumber);
while (nextFileNumber < usedCacheBlocks && !done) {
long shiftAmount = softMapping.getCurrentShiftAmount(lastIndexInBlock);
softMapping.removeShift(lastIndexInBlock);
//count of shifts done into current cache block
long shiftCount = 0;
//count of shifts done from next cache block
long nextShiftCount = 0;
List<E> cacheBlock = arrayLists.get(cacheBlockSpot);
List<E> nextCacheBlock = arrayLists.get(nextCacheBlockSpot);
//shift down to current block
while (cacheBlock.size() < getBlockSize() && !done) {
if (nextCacheBlock.size() > 0) {
cacheBlock.add(nextCacheBlock.remove(0));
cacheMapping.removeEntry(nextCacheBlockSpot);
cacheMapping.addEntry(cacheBlockSpot);
shiftCount++;
nextShiftCount++;
} else {
//next block is empty, reset nextShiftCount
if (nextShiftCount > 0) {
softMapping.addShift(lastIndexInNextBlock, nextShiftCount);
nextShiftCount = 0;
}
nextFileNumber++;
//not reached end of blocks
if (nextFileNumber < usedCacheBlocks) {
//next file is not in cache
if (!cacheMapping.isFileInCache(nextFileNumber)) {
done = true;
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
nextCacheBlock = arrayLists.get(nextCacheBlockSpot);
lastIndexInNextBlock = cacheMapping.getLastIndexInFile(nextFileNumber);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
} else {
done = true;
}
}
}
//may have ended loop without doing all shifts for current block
//add back in
if (shiftAmount - shiftCount > 0) {
softMapping.addShift(lastIndexInBlock, shiftAmount - shiftCount);
} else {
//current block = full
fileNumber++;
if (fileNumber == nextFileNumber) {
nextFileNumber = fileNumber + 1;
}
//if not at end
if (nextFileNumber < usedCacheBlocks) {
//add remaining shifts to next block
//no shifts to add to current block since it was filled
softMapping.addShift(lastIndexInNextBlock, nextShiftCount);
if (!cacheMapping.isFileInCache(fileNumber)) {
done = true;
} else {
cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
lastIndexInBlock = cacheMapping.getLastIndexInFile(fileNumber);
cacheMapping.setDirtyBit(cacheBlockSpot, true);
}
if (!cacheMapping.isFileInCache(nextFileNumber)) {
done = true;
} else {
nextCacheBlockSpot = cacheMapping.getCacheBlockSpot(nextFileNumber);
lastIndexInNextBlock = cacheMapping.getLastIndexInFile(nextFileNumber);
cacheMapping.setDirtyBit(nextCacheBlockSpot, true);
}
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Adds an element to the end of the list.
* Analogous to the add method of the ArrayList class
*
* @param element The element to add
* @return If the element was added or not
*/
public boolean add(E element) {
boolean added = false;
long adjustedIndex = softMapping.getAdjustedIndex(wholeListSize);
int lastFile = cacheMapping.getFileNumber(adjustedIndex);
int cacheBlockSpot = -1;
if (!cacheMapping.isFileInCache(lastFile)) {
//bring last file into cache
cacheMapping.bringFileIntoCache(lastFile);
}
cacheBlockSpot = cacheMapping.getCacheBlockSpot(lastFile);
//no -1 check, assumed it was brought in
//if last file is not full
if (!cacheMapping.isCacheFull(cacheBlockSpot)) {
//add to last array list and update cache entry
added = arrayLists.get(cacheBlockSpot).add(element);
if (added) {
cacheMapping.addEntry(cacheBlockSpot);
cacheMapping.setDirtyBit(cacheBlockSpot, true);
wholeListSize++;
}
} else {
throw new RuntimeException("Failed to add " + element + " at the end of the list");
}
return added;
}
/**
* Gets an element at the specified index.
* Analogous to the get method of the ArrayList class
*
* @param index The index
* @return The element
*/
public E get(long index) {
if (index < 0 || index >= wholeListSize) {
throw new IndexOutOfBoundsException(" " + index + " ");
}
//if index not in cache and not greater than max
//bring corresponding file in cache
long adjustedIndex = softMapping.getAdjustedIndex(index);
int fileNumber = cacheMapping.getFileNumber(adjustedIndex);
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheMapping.bringFileIntoCache(fileNumber);
}
int cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
//find cache that index is in
//find cache spot
//get from the cache spot
int spotInCache = cacheMapping.getSpotInCache(adjustedIndex);
return arrayLists.get(cacheBlockSpot).get(spotInCache);
}
/**
* Analogous to the get method of the ArrayList class
*
* @param index The index
* @return Returns the element at the specified index
*/
public E get(int index) {
long longIndex = index;
return get(longIndex);
}
/**
* Analogous to the remove method of the ArrayList class
*
* @param index The index
* @return Returns the element removed at the specified index
*/
public E remove(long index) {
if (index < 0 || index >= wholeListSize) {
throw new IndexOutOfBoundsException(" " + index + " ");
}
//can possibly add something to the buffer
//safest place to clear the buffer is here
if (softMapping.isBufferFull() || softMapping.isShiftMaxed()) {
purgeActionBuffer();
}
long adjustedIndex = softMapping.getAdjustedIndex(index);
int fileNumber = cacheMapping.getFileNumber(adjustedIndex);
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheMapping.bringFileIntoCache(fileNumber);
}
int cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
int spotInCache = cacheMapping.getSpotInCache(adjustedIndex);
long virtualSize = wholeListSize + softMapping.getLastShiftAmount();
int usedCacheBlocks = getNumberOfUsedBlocks(virtualSize);
List<E> cacheBlock = arrayLists.get(cacheBlockSpot);
E element = cacheBlock.remove(spotInCache);
cacheMapping.removeEntry(cacheBlockSpot);
cacheMapping.setDirtyBit(cacheBlockSpot, true);
//need to shift other lists down to the one where an element was just removed
//update SoftMapping for the remove action
long lastIndexInBlock = cacheMapping.getLastIndexInFile(fileNumber);
//if this block is the last block, no need to care about unnecessary shifts
if ((fileNumber + 1) < usedCacheBlocks) {
softMapping.addShift(lastIndexInBlock, 1);
purgeActionBufferInCache(lastIndexInBlock);
}
wholeListSize--;
return element;
}
/**
* Analogous to the remove method of the ArrayList class
*
* @param index The index
* @return Returns the element removed at the specified index
*/
public E remove(int index) {
long longIndex = index;
return remove(longIndex);
}
/**
* Sets the element at the specified index
* Analogous to the set method of the ArrayList class
*
* @param index The index
* @param element The new element
* @return The new element at the specified index
*/
public E set(long index, E element) {
if (index < 0 || index >= wholeListSize) {
throw new IndexOutOfBoundsException(" " + index + " ");
}
//if index not in cache and not greater than max
//bring corresponding file in cache
long adjustedIndex = softMapping.getAdjustedIndex(index);
int fileNumber = cacheMapping.getFileNumber(adjustedIndex);
if (!cacheMapping.isFileInCache(fileNumber)) {
cacheMapping.bringFileIntoCache(fileNumber);
}
int cacheBlockSpot = cacheMapping.getCacheBlockSpot(fileNumber);
//find cache that index is in
//find cache spot
//get from the cache spot
int spotInCache = cacheMapping.getSpotInCache(adjustedIndex);
cacheMapping.setDirtyBit(cacheBlockSpot, true);
return arrayLists.get(cacheBlockSpot).set(spotInCache, element);
}
/**
* Sets the element at the specified index
* Analogous to the set method of the ArrayList class
*
* @param index The index