Alles in open() und danach while (!stopped)-Schleife wird in die Datei gedruckt. Alles in der Methode pollAndPrintValues() wird nicht gedruckt. Was ist das Problem mit meinem Code?
Code: Select all
public class AsyncDataExporter implements Runnable
{
private static final String WHITESPACE = " ";
private final File file;
private final BufferedWriter out;
private final BlockingQueue queue = new LinkedBlockingQueue();
private final ExportData exportData;
private volatile boolean started = false;
private volatile boolean stopped = false;
private Data data;
private int valueCount = 0;
public AsyncDataExporter(File file, ExportData exportData) {
this.file = file;
this.exportData = exportData;
try {
this.out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
throw new ExportException("Could not initiate AsyncDataExporter", e);
}
}
public AsyncMeasurementCurveExporter append(Map values) {
if (!started) {
throw new MeasurementExportException("open() call expected before append()");
}
try {
queue.put(values);
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
return this;
}
public void open(Data data) {
this.data = data;
exportGeneralData();
this.started = true;
this.stopped = false;
new Thread(this).start();
}
public void run() {
try {
while (!stopped) {
try {
pollAndPrintValues();
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
}
write("end");
} catch (IOException ex) {
log.error("Could not write to file", ex);
} finally {
try {
out.close();
} catch (IOException ignore) {
log.error("Error on closing BufferedWriter", ignore);
}
}
}
public void close() {
this.stopped = true;
}
private void pollAndPrintValues() throws InterruptedException {
Map values = queue.poll(100, TimeUnit.MICROSECONDS);
if (values != null) {
try {
printValues(values);
out.flush();
} catch (IOException ex) {
log.error("Could not export data", ex);
throw new MeasurementExportException(ex);
}
}
}
private void write(String line) throws IOException {
out.write(line);
out.newLine();
}
...
}