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
|
/*
* Copyright (C) 2014-2021 Brian L. Browning
*
* This file is part of Beagle
*
* Beagle 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.
*
* Beagle 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 blbutil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* <p>Class {@code BlockLineReader} is a {@code blbutil.FileIt} that reads
* blocks of lines from a file. The order of lines in the source file is
* preserved by the returned string arrays. The {@code hasNext()} method
* always returns {@code true}. After the final block of lines is returned
* by the {@code next()} method, the {@code next()} method returns
* {@code BlockLineReader.SENTINAL} on all subsequent invocations.
* {@code BlockLineReader.SENTINAL} is guaranteed to be the only returned
* array that has length 0.
*
* <p>Instances of class {@code BlockLineReader} are thread-safe.</p>
*
* <p>Methods of this class will terminate the Java Virtual Machine with
* an error message if an I/O Exception is encountered.
* </p>
*
* @author Brian L. Browning {@code <browning@uw.edu>}
*/
public class BlockLineReader implements FileIt<String[]> {
/**
* The string array returned by {@code next()} after all blocks
* of lines have been read.
*/
public static String[] SENTINAL = new String[0];
private final FileIt<String> it;
private final LinkedBlockingDeque<String[]> q;
private final int blockSize;
private final ExecutorService fileReaderService;
private final CountDownLatch latch;
private volatile boolean shutDownNow;
/**
* Constructs and returns a new {@code BlockLineReader} for the specified
* data. The {@code close()} method of the returned object will invoke the
* {@code close()} method on the specified {@code FileIt<String>} iterator.
* The calling thread should not directly invoke any methods of the
* specified {@code FileIt<String>} after it is passed to the
* {@code BlockLineReader.create()} method.
* @param it a file iterator that returns the lines of text
* @param blockSize the maximum length a string array returned by
* {@code next()}
* @param nBlocks the maximum number of non-empty string arrays that will be
* buffered
* @return a {@code BlockLineReader} for the specified data.
* @throws IllegalArgumentException if {@code blockSize < 1 || nBlocks < 1}
* @throws NullPointerException if {@code it == null}
*/
public static BlockLineReader create(FileIt<String> it, int blockSize,
int nBlocks) {
BlockLineReader reader = new BlockLineReader(it, blockSize, nBlocks);
reader.startFileReadingThread();
return reader;
}
private BlockLineReader(FileIt<String> it, int blockSize, int nBlocks) {
if (blockSize<1) {
throw new IllegalArgumentException(String.valueOf(blockSize));
}
if (nBlocks<1) {
throw new IllegalArgumentException(String.valueOf(nBlocks));
}
this.it = it;
this.q = new LinkedBlockingDeque<>(nBlocks);
this.blockSize = blockSize;
this.fileReaderService = Executors.newSingleThreadExecutor();
this.latch = new CountDownLatch(1);
this.shutDownNow = false;
}
private void startFileReadingThread() {
fileReaderService.submit(() -> {
try {
List<String> buffer = new ArrayList<>(blockSize);
while (it.hasNext()) {
buffer.add(it.next());
if (buffer.size()==blockSize) {
flushBuffer(buffer);
if (shutDownNow) {
break;
}
}
}
if (buffer.size()>0) {
flushBuffer(buffer);
}
latch.countDown();
MultiThreadUtils.putInBlockingQ(q, SENTINAL);
}
catch (Throwable t) {
Utilities.exit(t);
}
});
}
/*
* Returns {@code false} if no more blocks of lines will be enqueued.
*/
private void flushBuffer(List<String> buffer) {
String[] sa = buffer.toArray(new String[0]);
buffer.clear();
boolean success = false;
while (success==false && shutDownNow==false) {
success = MultiThreadUtils.putInBlockingQ(q, sa, 100,
TimeUnit.MILLISECONDS);
}
}
@Override
public File file() {
return it.file();
}
@Override
public void close() {
shutDownNow = true;
MultiThreadUtils.await(latch);
it.close();
String[] tail = q.pollLast();
while (tail!=null && tail!=SENTINAL) {
tail = q.pollLast();
}
if (tail==SENTINAL) {
boolean success = q.offer(SENTINAL);
assert success;
}
MultiThreadUtils.shutdownExecService(fileReaderService);
}
/**
* Returns {@code true}. The {@code this.next()} method will return
* {@code BlockLineReader.SENTINAL} if the iterations has no
* more elements.
* @return {@code true}
*/
@Override
public boolean hasNext() {
return true;
}
/**
* Returns the next element in the iteration. Returns
* {@code BlockLineReader.SENTINAL} if the iterations has no
* more elements.
* @return the next element in the iteration
*/
@Override
public String[] next() {
assert hasNext();
String[] value = MultiThreadUtils.takeFromBlockingQ(q);
if (value==SENTINAL) {
boolean success = q.offer(SENTINAL);
assert success;
}
return value;
}
/**
* The {@code remove} method is not supported by this iterator.
* @throws UnsupportedOperationException if this method is invoked
*/
@Override
public void remove() {
throw new UnsupportedOperationException(this.getClass().toString());
}
}
|