Tomcat7上でServlet3.0のasync-supportedを使ってみる

今回作成したソースはgithub上に置いてあります。下記参照。
https://github.com/bose999/servlet30-tomcat7-sample


ServletにてAsyncContextを生成
非同期処理のイベント発生時に処理をするAsyncListenerをセット
AsyncContextのstartメッソドでRunnableを実装した非同期処理をキックする
という流れ。

AsyncContext asyncContext = request.startAsync();
SampleAsyncListener sampleAsyncListener = new SampleAsyncListener();
asyncContext.addListener(sampleAsyncListener);

AsyncAction asyncAction = new AsyncAction(asyncContext);

// 別スレッドで処理実行しこのスレッドは解放する
// 別スレッドはSampleAsyncListenerによってイベント処理される
asyncContext.start(asyncAction);


サンプルを実行すると下記のように各クラスが
別スレッドで処理を行う事がわかる。

2012-04-22 10:09:45.889 JST TRACE [http-bio-8080-exec-6] jp.techie.sample.servlet.SampleServlet - Line:48 Start doGet Method
2012-04-22 10:09:45.905 JST TRACE [http-bio-8080-exec-6] jp.techie.sample.servlet.SampleServlet - Line:63 End doGet Method:19ms.
2012-04-22 10:09:45.905 JST TRACE [http-bio-8080-exec-7] jp.techie.sample.servlet.AsyncAction - Line:59 Start AsyncAction
2012-04-22 10:09:45.907 JST TRACE [http-bio-8080-exec-7] jp.techie.sample.servlet.AsyncAction - Line:65 /WEB-INF/jsp/result.jsp
2012-04-22 10:09:45.909 JST TRACE [http-bio-8080-exec-7] jp.techie.sample.servlet.AsyncAction - Line:73 End AsyncAction:4ms.
2012-04-22 10:09:45.984 JST TRACE [http-bio-8080-exec-8] jp.techie.sample.servlet.SampleAsyncListener - Line:48 onComplete