Skip to content

Instantly share code, notes, and snippets.

@rschildmeijer
Created July 19, 2011 05:55
Show Gist options
  • Save rschildmeijer/1091426 to your computer and use it in GitHub Desktop.
Save rschildmeijer/1091426 to your computer and use it in GitHub Desktop.
Adam Lofts blocking request handler
package org.apache.deft.example;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.deftserver.io.IOLoop;
import org.deftserver.web.Application;
import org.deftserver.web.AsyncCallback;
import org.deftserver.web.Asynchronous;
import org.deftserver.web.HttpServer;
import org.deftserver.web.handler.RequestHandler;
import org.deftserver.web.http.HttpRequest;
import org.deftserver.web.http.HttpResponse;
public class BlockingRequestHandler extends RequestHandler {
private final ExecutorService worker = Executors.newSingleThreadExecutor();
@Override
@Asynchronous
public void get(HttpRequest request, final HttpResponse response) {
worker.execute(new Runnable() { public void run() {doGet(response); }});
}
private void doGet(final HttpResponse response) {
//Simulate work
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) { }
// We could invoke response.finish() by this thread. But it's not threadsafe. Instead we are adding a
// "generic" callback (a piece of code) that will be invoked by the ioloop thread in the next io iteration.
IOLoop.INSTANCE.addCallback(new AsyncCallback() { public void onCallback() { response.finish(); }});
}
public static void main(String[] args) {
Map<String, RequestHandler> handlers = new HashMap<String, RequestHandler>();
handlers.put("/", new BlockingRequestHandler());
HttpServer server = new HttpServer(new Application(handlers));
server.listen(8080);
IOLoop.INSTANCE.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment