4
我一直在嘗試使用異步上下文的超時功能。但行爲是高度間歇的。有時會發生超時,很多時候不會。我在這裏粘貼我的代碼。異步上下文不超時
@WebServlet(name = "TestServlet", urlPatterns = {"/test"},asyncSupported = true)
public class TestServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static PriorityBlockingQueue<Runnable> pq = new PriorityBlockingQueue<Runnable>(1000);
private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,1,10, TimeUnit.SECONDS,pq);
public void service(final ServletRequest servletRequest, final ServletResponse response)
throws ServletException, IOException {
TestListener listener = new TestListener();
final AsyncContext asyncContext = servletRequest.startAsync();
asyncContext.addListener(listener);
asyncContext.setTimeout(100);
Handler handler = new Handler(asyncContext);
threadPoolExecutor.execute(handler);
}
}
偵聽器和處理程序代碼包含在下面。
public class TestListener implements AsyncListener {
public void onComplete(AsyncEvent event) throws IOException {
System.out.println("Event completed");
}
public void onError(AsyncEvent event) throws IOException {
event.getAsyncContext().complete();
}
public void onStartAsync(AsyncEvent event) throws IOException {
// TODO Auto-generated method stub
}
public void onTimeout(AsyncEvent event){
System.out.println("Timeout ");
event.getAsyncContext().complete();
}
}
public class Handler implements Runnable {
private AsyncContext asyncContext;
public Handler(AsyncContext asyncContext){
this.asyncContext = asyncContext;
}
public void run(){
try {
long currtime = System.currentTimeMillis();
Thread.sleep(500);
System.out.println("slept for " + (System.currentTimeMillis() - currtime));
} catch (InterruptedException e) {
System.out.println("Error in thread ");
}
try{
if(asyncContext != null){
System.out.println("Completing async context " + " timeout is " + asyncContext.getTimeout());
asyncContext.complete();
}
}catch (Exception e){
System.out.println("Exception in completing async context ");
}
}
}
而且輸出是間歇性的。包括同樣在這裏 -
[[email protected] combinedlogs]$ time curl "http://localhost:9001/mockresponse/test"
real 0m0.506s
user 0m0.001s
sys 0m0.003s
[[email protected] combinedlogs]$ time curl "http://localhost:9001/mockresponse/test"
real 0m0.159s
user 0m0.001s
sys 0m0.003s
卡塔利娜日誌 -
slept for 500
Completing async context timeout is 100
Event completed
Timeout
Event completed
slept for 500
Exception in completing async context
我不明白爲什麼會這樣。請幫忙!謝謝你的時間。
PS:將tomcat版本7.0.37
謝謝您的回覆!更高的超時時間和睡眠值確保在每種情況下都超時。我也早點檢查過它!但是,當我的超時時間可以從100毫秒到10000毫秒時,它不適合我的目的。我之前也經歷過這個bug,所以我決定使用最新版本的tomcat。無論如何,我不認爲我可以使用上下文超時,我寧願使用計時器線程或HashWheeledTimer。謝謝! – 2013-05-14 06:24:16