
com.sampullara.util.FutureWriter Maven / Gradle / Ivy
The newest version!
package com.sampullara.util;
import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.sampullara.mustache.Mustache;
import com.sampullara.mustache.MustacheTrace;
/**
* This class sit in front of a writer and doesn't flush until Done is called on it. Until then it queues up
* writes that may not even be completed yet. They are flushed out in the order they are enqueued.
*
* User: sam
* Date: May 6, 2010
* Time: 2:44:42 PM
*/
public class FutureWriter extends Writer {
private AppendableCallable last;
private ConcurrentLinkedQueue> ordered = new ConcurrentLinkedQueue>();
private static ExecutorService des;
private ExecutorService es;
private Writer writer;
private boolean closed = false;
public static void setParallel() {
setParallel(new MustacheExecutor());
}
public static void setParallel(ExecutorService es) {
ExecutorService old = FutureWriter.des;
// Switch to the new one
FutureWriter.des = es;
// Gracefully shutdown the old one
if (old != null) old.shutdown();
}
public FutureWriter() {
es = des;
}
public FutureWriter(Writer writer) {
this();
this.writer = writer;
}
public Writer getWriter() {
return writer;
}
public void setWriter(Writer writer) {
this.writer = writer;
}
public static void shutdown() {
if (des != null) {
des.shutdownNow();
}
}
/**
* Optimize for the degenerate case of a set of strings being appended to the writer.
*
* @param cs
* @throws IOException
*/
private void enqueue(CharSequence cs) throws IOException {
if (closed) {
throw new IOException("closed");
}
if (isParallel()) {
if (last != null) {
last.append(cs);
} else {
AppendableCallable call = new AppendableCallable(cs);
enqueue(call);
last = call;
}
} else {
if (cs != null) {
writer.write(cs.toString());
}
}
}
public void enqueue(Callable
© 2015 - 2025 Weber Informatics LLC | Privacy Policy