-
Notifications
You must be signed in to change notification settings - Fork 4
/
IndexWriter.java
2830 lines (2452 loc) · 90.6 KB
/
IndexWriter.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 (c) 2008, 2023 SAP AG, IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* SAP AG - initial API and implementation
* Andrew Johnson - enhancements for huge dumps
* Netflix (Jason Koch) - refactors for increased performance and concurrency
*******************************************************************************/
package org.eclipse.mat.parser.index;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.mat.collect.ArrayInt;
import org.eclipse.mat.collect.ArrayIntCompressed;
import org.eclipse.mat.collect.ArrayLong;
import org.eclipse.mat.collect.ArrayLongBig;
import org.eclipse.mat.collect.ArrayLongCompressed;
import org.eclipse.mat.collect.ArrayUtils;
import org.eclipse.mat.collect.BitField;
import org.eclipse.mat.collect.HashMapIntLong;
import org.eclipse.mat.collect.HashMapIntObject;
import org.eclipse.mat.collect.HashMapIntObject.Entry;
import org.eclipse.mat.collect.IteratorInt;
import org.eclipse.mat.collect.IteratorLong;
import org.eclipse.mat.collect.SetInt;
import org.eclipse.mat.parser.index.IIndexReader.IOne2LongIndex;
import org.eclipse.mat.parser.index.IIndexReader.IOne2OneIndex;
import org.eclipse.mat.parser.index.IndexReader.SizeIndexReader;
import org.eclipse.mat.parser.internal.Messages;
import org.eclipse.mat.parser.internal.snapshot.RetainedSizeCache;
import org.eclipse.mat.parser.io.BitInputStream;
import org.eclipse.mat.parser.io.BitOutputStream;
import org.eclipse.mat.util.IProgressListener;
import org.eclipse.mat.util.MessageUtil;
/**
* Base implementations to write index files.
*/
public abstract class IndexWriter
{
/** Number of entries in a page of ints */
public static final int PAGE_SIZE_INT = 1000000;
/** Number of entries in a page of longs */
public static final int PAGE_SIZE_LONG = 500000;
/** Set this to true to test more code paths with smaller indices */
private static final boolean TEST = false;
/** How much to resize break points for large formats to make testing easier */
private static final int TESTSCALE = TEST ? 18 : 0;
/** Switch point from plain size to encoded size for 1 to 1 index */
private static final int FORMAT1_MAX_SIZE = Integer.MAX_VALUE >>> TESTSCALE;
/** Switch point for using a long valued header index */
private static final long MAX_OLD_HEADER_VALUE = 0xffffffffL >>> TESTSCALE;
/** Switch point for inbound key to using longs */
private static final long INBOUND_MAX_KEY1 = Integer.MAX_VALUE >>> TESTSCALE;
private static final Logger logger = Logger.getLogger(RetainedSizeCache.class.getName());
/**
* Used to write out a key for an index.
*/
public interface KeyWriter
{
/**
* Store the key in a file
* @param index the index
* @param key the corresponding key to another index
*/
public void storeKey(int index, Serializable key);
}
// //////////////////////////////////////////////////////////////
// integer based indices
// //////////////////////////////////////////////////////////////
/**
* Used to collect the objects by address.
*/
public static class Identifier implements IIndexReader.IOne2LongIndex
{
long[] identifiers;
int size;
ArrayLongBig collect;
/**
* Add an object.
* @param id the object address
*/
public void add(long id)
{
if (collect == null)
collect = new ArrayLongBig();
// Avoid strange exceptions later
int s = collect.length();
long minCapacity = size + s + 1;
int newCapacity = Math.min((int)minCapacity, Integer.MAX_VALUE - 8);
if (newCapacity < minCapacity)
{
throw new OutOfMemoryError(MessageUtil.format(Messages.IndexWriter_Error_ArrayLength, minCapacity, newCapacity));
}
collect.add(id);
}
/**
* Sort the addresses of the objects in order.
* Also puts all of the added addresses into an array.
* Makes a reverse lookup easier.
*/
public void sort()
{
if (collect == null)
{
}
else if (identifiers == null)
{
size = collect.length();
identifiers = collect.toArray();
collect = null;
}
else
{
int s = collect.length();
long minCapacity = size + s;
int newCapacity = Math.min((int)minCapacity, Integer.MAX_VALUE - 8);
if (newCapacity < minCapacity)
{
// Avoid strange exceptions later
throw new OutOfMemoryError(MessageUtil.format(Messages.IndexWriter_Error_ArrayLength, minCapacity, newCapacity));
}
identifiers = copyOf(identifiers, newCapacity);
for (int i = 0; i < s; ++i)
{
identifiers[size + i] = collect.get(i);
}
size += s;
collect = null;
}
Arrays.parallelSort(identifiers, 0, size);
Arrays.sort(identifiers, 0, size); // Debug for bug 581932
}
public int size()
{
return size + (collect != null ? collect.length() : 0);
}
public long get(int index)
{
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size()); //$NON-NLS-1$//$NON-NLS-2$
return index < size || collect == null ? identifiers[index] : collect.get(index - size);
}
public int reverse(long val)
{
int a, c;
// Just search up to size, as anything in collect probably hasn't been sorted
for (a = 0, c = size; a < c;)
{
// Avoid overflow problems by using unsigned divide by 2
int b = (a + c) >>> 1;
long probeVal = get(b);
if (val < probeVal)
{
c = b;
}
else if (probeVal < val)
{
a = b + 1;
}
else
{
return b;
}
}
// Negative index indicates not found (and where to insert)
return -1 - a;
}
/**
* Iterate through the object addresses.
* @return the iterator
*/
public IteratorLong iterator()
{
return new IteratorLong()
{
int index = 0;
public boolean hasNext()
{
return index < size();
}
public long next()
{
return get(index++);
}
};
}
public long[] getNext(int index, int length)
{
long answer[] = new long[length];
for (int ii = 0; ii < length; ii++)
answer[ii] = get(index + ii);
return answer;
}
public void close() throws IOException
{}
public void delete()
{
identifiers = null;
collect = null;
}
public void unload() throws IOException
{
throw new UnsupportedOperationException();
}
}
/**
* Collect a mapping of int to int.
*/
public static class IntIndexCollectorUncompressed
{
int[] dataElements;
/**
* Create an IntIndexCollectorUncompressed of the given size.
* @param size the requiredsize
*/
public IntIndexCollectorUncompressed(int size)
{
dataElements = new int[size];
}
/**
* Set a particular entry.
* @param index the index into the array
* @param value the value
*/
public void set(int index, int value)
{
dataElements[index] = value;
}
/**
* Retrieve an entry.
* @param index the index
* @return the value
*/
public int get(int index)
{
return dataElements[index];
}
/**
* Store the collector to a file.
* @param indexFile the file
* @return an index which holds the same values as the collector
* @throws IOException if a problem occurred with the write
*/
public IIndexReader.IOne2OneIndex writeTo(File indexFile) throws IOException
{
return new IntIndexStreamer().writeTo(indexFile, dataElements);
}
}
/**
* Store sizes of objects by
* compressing the size to a 32-bit int.
* @since 1.0
*/
public static class SizeIndexCollectorUncompressed extends IntIndexCollectorUncompressed
{
/**
* Create a collector of the required size.
* @param size the number of entries
*/
public SizeIndexCollectorUncompressed(int size)
{
super(size);
}
/**
* Cope with objects of size in bytes bigger than Integer.MAX_VALUE.
* E.g. double[Integer.MAX_VALUE]
* The original problem was that the array to size mapping had an integer as the size (IntIndexCollectorUncompressed).
* This array would be approximately 0x18 + 0x8 * 0x7fffffff = 0x400000010 bytes, too big for an int.
* Expanding the array size array to longs could be overkill.
* Instead we do some simple compression - values 0 - 0x7fffffff convert as now,
* int values 0x80000000 to 0xffffffff convert to <code>(n & 0x7fffffffL)*8 + 0x80000000L</code>.
* @param y the long value in the range -1 to 0x7fffffff, 0x80000000L to 0x400000000L
* @return the compressed value as an int
*/
public static int compress(long y)
{
int ret;
if (y < 0)
ret = -1;
else if (y <= Integer.MAX_VALUE)
ret = (int) y;
else if (y <= 0x400000000L)
{
ret = (int) (y / 8) + 0x70000000;
}
else
ret = 0xf0000000;
return ret;
}
/**
* Expand the result of the compression
* @param x the compressed value
* @return the expanded value as a long in the range -1 to 0x7fffffff, 0x80000000L to 0x400000000L
*/
public static long expand(int x) {
long ret;
if (x >= -1)
ret = x;
else if (x < 0xf0000000)
{
ret = (x & 0x7fffffffL) * 8 + 0x80000000L;
}
else
ret = 0x400000000L;
return ret;
}
/**
* Set the size for an object.
* @param index the object ID
* @param value the size
*/
public void set(int index, long value)
{
set(index, compress(value));
}
/**
* Get the expanded size.
* @param index the object ID
* @return the size
*/
public long getSize(int index)
{
int v = get(index);
return expand(v);
}
public IIndexReader.IOne2SizeIndex writeTo(File indexFile) throws IOException
{
return new SizeIndexReader(new IntIndexStreamer().writeTo(indexFile, dataElements));
}
}
static class Pages<V>
{
int size;
Object[] elements;
public Pages(int initialSize)
{
elements = new Object[initialSize];
size = 0;
}
private void ensureCapacity(int minCapacity)
{
int oldCapacity = elements.length;
if (minCapacity > oldCapacity)
{
int newCapacity = newCapacity(oldCapacity, minCapacity);
if (newCapacity < minCapacity)
{
// Avoid strange exceptions later
throw new OutOfMemoryError(MessageUtil.format(Messages.IndexWriter_Error_ObjectArrayLength, minCapacity, newCapacity));
}
Object[] copy = new Object[newCapacity];
System.arraycopy(elements, 0, copy, 0, Math.min(elements.length, newCapacity));
elements = copy;
}
}
@SuppressWarnings("unchecked")
public V get(int key)
{
return (key >= elements.length) ? null : (V) elements[key];
}
public void put(int key, V value)
{
ensureCapacity(key + 1);
elements[key] = value;
size = Math.max(size, key + 1);
}
public int size()
{
return size;
}
}
abstract static class IntIndex<V>
{
int pageSize;
long size;
Pages<V> pages;
protected IntIndex()
{}
protected IntIndex(int size)
{
init(size, PAGE_SIZE_INT);
}
protected void init(int size, int pageSize)
{
this.size = size;
this.pageSize = pageSize;
this.pages = new Pages<V>(size / pageSize + 1);
}
void init(long size, int pageSize)
{
this.size = size;
this.pageSize = pageSize;
this.pages = new Pages<V>((int)(size / pageSize) + 1);
}
public int get(int index)
{
// Should we allow index to be unsigned?
return get0(index);
}
int get(long index)
{
if (index == (int)index)
{
// in case get(int) is overridden
return get((int)index);
}
else
{
return get0(index);
}
}
private int get0(long index)
{
int page = page(index);
int pageIndex = offset(index);
ArrayIntCompressed array = getPage(page);
return array.get(pageIndex);
}
long getPos(int index)
{
// Should we allow index to be unsigned?
return get(index) & 0xffffffffL;
}
private int page(int index)
{
return index / pageSize;
}
private int offset(int index)
{
return index % pageSize;
}
int page(long index)
{
return (int)(index / pageSize);
}
int offset(long index)
{
return (int)(index % pageSize);
}
public int[] getNext(int index, int length)
{
// Should we allow index to be unsigned?
return getNext0(index, length);
}
int[] getNext(long index, int length)
{
if (index == (int)index)
{
// in case getNext(int, int) is overridden
return getNext((int)index, length);
}
else
{
return getNext0(index, length);
}
}
private int[] getNext0(long index, int length)
{
int answer[] = new int[length];
if (length == 0)
return answer;
int page = page(index);
int pageIndex = offset(index);
ArrayIntCompressed array = getPage(page);
for (int ii = 0; ii < length; ii++)
{
answer[ii] = array.get(pageIndex++);
if (pageIndex >= pageSize && ii + 1 < length)
{
array = getPage(++page);
pageIndex = 0;
}
}
return answer;
}
public int[] getAll(int index[])
{
int[] answer = new int[index.length];
int page = -1;
ArrayIntCompressed array = null;
for (int ii = 0; ii < answer.length; ii++)
{
int p = page(index[ii]);
if (p != page)
array = getPage(page = p);
answer[ii] = array.get(offset(index[ii]));
}
return answer;
}
public void set(int index, int value)
{
ArrayIntCompressed array = getPage(page(index));
array.set(offset(index), value);
}
protected abstract ArrayIntCompressed getPage(int page);
public synchronized void unload()
{
this.pages = new Pages<V>(page(size) + 1);
}
public int size()
{
if (size > Integer.MAX_VALUE)
throw new IllegalStateException();
return (int)Math.min(Integer.MAX_VALUE, size);
}
public IteratorInt iterator()
{
return new IntIndexIterator(this);
}
}
static class IntIndexIterator implements IteratorInt
{
IntIndex<?> intArray;
long nextIndex = 0;
public IntIndexIterator(IntIndex<?> intArray)
{
this.intArray = intArray;
}
public int next()
{
return intArray.get(nextIndex++);
}
public boolean hasNext()
{
return nextIndex < intArray.size;
}
}
/**
* A collector of ArrayIntCompressed.
*/
public static class IntIndexCollector extends IntIndex<ArrayIntCompressed> implements IOne2OneIndex
{
final int mostSignificantBit;
final int size;
final int pageSize = IndexWriter.PAGE_SIZE_INT;
final ConcurrentHashMap<Integer, ArrayIntCompressed> pages = new ConcurrentHashMap<Integer, ArrayIntCompressed>();
/**
* Construct a collector of the required size, holding int
* values up to the specified size.
* @param size the number of entries
* @param mostSignificantBit the most significant bit set of any entry
*/
public IntIndexCollector(int size, int mostSignificantBit)
{
this.size = size;
this.mostSignificantBit = mostSignificantBit;
}
protected ArrayIntCompressed getPage(int page)
{
ArrayIntCompressed existing = pages.get(page);
if (existing != null) return existing;
int ps = page < (size / pageSize) ? pageSize : size % pageSize;
ArrayIntCompressed newArray = new ArrayIntCompressed(ps, 31 - mostSignificantBit, 0);
existing = pages.putIfAbsent(page, newArray);
return (existing != null) ? existing : newArray;
}
/**
* Write the collector to a file.
* @param indexFile the file
* @return an index which holds the same values as the collector
* @throws IOException if a problem occurred with the write
*/
public IIndexReader.IOne2OneIndex writeTo(File indexFile) throws IOException
{
// needed to re-compress
return new IntIndexStreamer().writeTo(indexFile, new IteratorInt()
{
int index = 0;
public boolean hasNext()
{
return (index < size);
}
public int next()
{
return get(index++);
}
});
}
public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position) throws IOException
{
// needed to re-compress
return new IntIndexStreamer().writeTo(out, position, new IteratorInt()
{
int index = 0;
public boolean hasNext()
{
return (index < size);
}
public int next()
{
return get(index++);
}
});
}
public void set(int index, int value)
{
ArrayIntCompressed array = getPage(index / pageSize);
synchronized(array)
{
array.set(index % pageSize, value);
}
}
public int get(int index)
{
// set() only happens during parsing stage, get later
ArrayIntCompressed array = getPage(index / pageSize);
return array.get(index % pageSize);
}
public void close() throws IOException
{ }
public void delete()
{
pages.clear();
}
public int size()
{
return size;
}
public void unload()
{
throw new UnsupportedOperationException(Messages.IndexWriter_NotImplemented);
}
public int[] getAll(int[] index)
{
throw new UnsupportedOperationException(Messages.IndexWriter_NotImplemented);
}
public int[] getNext(int index, int length)
{
throw new UnsupportedOperationException(Messages.IndexWriter_NotImplemented);
}
}
/**
* A helper to write out an index to a file.
*/
public static class IntIndexStreamer extends IntIndex<SoftReference<ArrayIntCompressed>>
{
DataOutputStream out;
ArrayLong pageStart;
int[] page;
int left;
// tracks number of pages added, may not be available if they are still being compressed
int pagesAdded;
// if the writer task has an exception during async we want to throw it on the next write
Exception storedException = null;
// if the writer task has an OutOfMemoryError during async we want to throw it on the next write
OutOfMemoryError storedError = null;
// Writer _must_ be single thread to ensure page update logic stays correct. Compressor
// could be, but generally not limited by compression speed, so one is enough.
final ExecutorService compressor = singleThreadedExecutor("IntIndexStreamer-Compressor"); //$NON-NLS-1$
final ExecutorService writer = singleThreadedExecutor("IntIndexStreamer-Writer"); //$NON-NLS-1$
public IIndexReader.IOne2OneIndex writeTo(File indexFile, IteratorInt iterator) throws IOException
{
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile)));
openStream(out, 0);
addAll(iterator);
closeStream();
out.close();
return getReader(indexFile);
}
/**
* Write an array to a file and return an index reader.
* @param indexFile the file
* @param array the array to write out
* @return the index reader
* @throws IOException if a problem occurs with the write
*/
public IIndexReader.IOne2OneIndex writeTo(File indexFile, int[] array) throws IOException
{
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile)));
openStream(out, 0);
addAll(array);
closeStream();
out.close();
return getReader(indexFile);
}
/**
* Write out a page at a particular position.
* @param out the output stream
* @param position the position of the data
* @param iterator where the data comes from
* @return a reader for the data written so far
* @throws IOException if the is a problem with the write
*/
public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position, IteratorInt iterator)
throws IOException
{
openStream(out, position);
addAll(iterator);
closeStream();
return getReader(null);
}
/**
* Write out a page at a particular position.
* @param out the output stream
* @param position the position of the data
* @param array where the data comes from
* @return a reader for the data written so far
* @throws IOException if the is a problem with the write
*/
public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position, int[] array) throws IOException
{
openStream(out, position);
addAll(array);
closeStream();
return getReader(null);
}
void openStream(DataOutputStream out, long position)
{
this.out = out;
init(0, PAGE_SIZE_INT);
this.page = new int[pageSize];
this.pageStart = new ArrayLong();
this.pageStart.add(position);
this.left = page.length;
}
/**
* @return total bytes written to index file
*/
long closeStream() throws IOException
{
try
{
if (left < page.length)
addPage();
else
new WriterTask(null); // Dummy to test for pending exception
}
catch (IOException e)
{
// Early termination with an exception
try
{
compressor.shutdownNow();
compressor.awaitTermination(100, TimeUnit.SECONDS);
writer.shutdownNow();
writer.awaitTermination(100, TimeUnit.SECONDS);
throw e;
}
catch (InterruptedException ie)
{
throw new IOException(ie);
}
}
try
{
compressor.shutdown();
compressor.awaitTermination(100, TimeUnit.SECONDS);
writer.shutdown();
writer.awaitTermination(100, TimeUnit.SECONDS);
}
catch (InterruptedException ie)
{
throw new IOException(ie);
}
// write header information
for (int jj = 0; jj < pageStart.size(); jj++)
out.writeLong(pageStart.get(jj));
out.writeInt(pageSize);
// Encoded size is the negative number of entries in the last page
int s = size <= FORMAT1_MAX_SIZE ? (int)size : -(int)((size + pageSize - 1) % pageSize + 1);
out.writeInt(s);
this.page = null;
this.out = null;
return this.pageStart.lastElement() + (8L * pageStart.size()) + 8 - this.pageStart.firstElement();
}
IndexReader.IntIndexReader getReader(File indexFile)
{
return new IndexReader.IntIndexReader(indexFile, pages, size, pageSize, pageStart.toArray());
}
void addAll(IteratorInt iterator) throws IOException
{
while (iterator.hasNext())
add(iterator.next());
}
void add(int value) throws IOException
{
if (left == 0)
addPage();
page[page.length - left--] = value;
size++;
}
void addAll(int[] values) throws IOException
{
addAll(values, 0, values.length);
}
void addAll(int[] values, int offset, int length) throws IOException
{
while (length > 0)
{
if (left == 0)
addPage();
int chunk = Math.min(left, length);
System.arraycopy(values, offset, page, page.length - left, chunk);
left -= chunk;
size += chunk;
length -= chunk;
offset += chunk;
}
}
long addAllWithLengthFirst(int[] values, int offset, int length) throws IOException
{
long startPos = size;
add(length);
addAll(values, offset, length);
return startPos;
}
private void addPage() throws IOException
{
Future<byte[]> compressionResult = compressor.submit(new CompressionTask(page, left, pagesAdded));
// compression may finish in any order, but writes have to be correct, so order them
writer.execute(new WriterTask(compressionResult));
pagesAdded += 1;
page = new int[page.length];
left = page.length;
}
@Override
protected ArrayIntCompressed getPage(int page)
{
throw new UnsupportedOperationException();
}
/*
* Compresses a page of data to a byte array
*/
private class CompressionTask implements Callable<byte[]>
{
final int[] page;
final int left;
final int pageNumber;
public CompressionTask(final int[] page, final int left, final int pageNumber)
{
this.page = page;
this.left = left;
this.pageNumber = pageNumber;
}
public byte[] call()
{
ArrayIntCompressed array = new ArrayIntCompressed(page, 0, page.length - left);
pages.put(pageNumber, new SoftReference<ArrayIntCompressed>(array));
return array.toByteArray();
}
}