Search in sources :

Example 1 with WriterOutputStream

use of org.jboss.stdio.WriterOutputStream in project wildfly by wildfly.

the class SimpleServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final String msg = req.getParameter("input");
    // the first call needs to be concurrent
    //bean.setMessage(msg);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final CountDownLatch latch = new CountDownLatch(1);
    final Future<String>[] futures = new Future[2];
    for (int i = 0; i < futures.length; i++) {
        futures[i] = executor.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                try {
                    return bean.echo(latch, msg);
                } finally {
                    // the second concurrent call will throw ConcurrentAccessException
                    // so now we make the first call proceed
                    latch.countDown();
                }
            }
        });
    }
    final List<String> results = new LinkedList<String>();
    final List<Throwable> exceptions = new LinkedList<Throwable>();
    for (int i = 0; i < futures.length; i++) {
        try {
            String result = futures[i].get(10, SECONDS);
            results.add(result);
        } catch (ExecutionException e) {
            e.printStackTrace();
            exceptions.add(e.getCause());
        } catch (InterruptedException e) {
            e.printStackTrace();
            exceptions.add(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
            exceptions.add(e);
        }
    }
    // make a 'nice' report
    PrintWriter writer = resp.getWriter();
    XMLEncoder encoder = new XMLEncoder(new WriterOutputStream(writer));
    encoder.writeObject(results);
    encoder.writeObject(exceptions);
    encoder.writeObject(sharedContext);
    encoder.close();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) WriterOutputStream(org.jboss.stdio.WriterOutputStream) Callable(java.util.concurrent.Callable) LinkedList(java.util.LinkedList) XMLEncoder(java.beans.XMLEncoder) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) PrintWriter(java.io.PrintWriter)

Aggregations

XMLEncoder (java.beans.XMLEncoder)1 PrintWriter (java.io.PrintWriter)1 LinkedList (java.util.LinkedList)1 Callable (java.util.concurrent.Callable)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 ExecutorService (java.util.concurrent.ExecutorService)1 Future (java.util.concurrent.Future)1 TimeoutException (java.util.concurrent.TimeoutException)1 WriterOutputStream (org.jboss.stdio.WriterOutputStream)1