简化在 InfoQ 上看到的一段的代码

刚在 InfoQ 上看了篇文章,讲的是 Servlet 3.0 的异步特性(当然这个特性有段时间了)。链接在此。不过我想说的不是 Servlet 3.0 的什么异步特性,而是想说说这篇文章里的示例代码的问题。


thread = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(2000);
                AsyncContext context;
                while ((context = queue.poll()) != null) {
                    try {
                        ServletResponse response = context.getResponse();
                        response.setContentType("text/plain");
                        PrintWriter out = response.getWriter();
                        out.printf("Thread %s completed the task", Thread.currentThread().getName());
                        out.flush();
                    } catch (Exception e) {
                        throw new RuntimeException(e.getMessage(), e);
                    } finally {
                        context.complete();
                    }
                }
            } catch (InterruptedException e) {
               return;
            }
        }
    }
});
thread.start();

从这个代码我们可以感觉到,这个貌似有点复杂,两个 while 两个 try catch。但其实这段代码完全可以写的很简单。

第一个 while(true) 的作用在于轮询 queue。但其实可以用 BlockingQueue 的 take() 方法取代 poll(),这样在队列为空时,线程会等待在那里,从而省去一个 while 循环。

至于两个 try catch,我就不多说了。

你可能感兴趣的:(简化在 InfoQ 上看到的一段的代码)