I am exploring async servlets using Spring boot. As far as I understand, async servlets are used to execute long running tasks in a thread other than the one which container launches to handle the request, so that container can use its own thread for handling other connections. Based on this understanding, I tried the following code:
@WebServlet(asyncSupported = true, urlPatterns = "/demo")
@Component
public class demo extends HttpServlet {
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final AsyncContext context = request.startAsync();
ServletOutputStream stream = response.getOutputStream();
WriteListener listener = new WriteListener() {
@Override
public void onWritePossible() throws IOException {
System.out.println(Thread.currentThread().getId());
ServletOutputStream output = context.getResponse().getOutputStream();
if (output.isReady()) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output.print("Heloooooooooo");
}
context.complete();
}
@Override
public void onError(Throwable throwable) {
throwable.printStackTrace(System.err);
context.complete();
}
};
stream.setWriteListener(listener);
System.out.println(Thread.currentThread().getId());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// TODO Auto-generated method stub
}
}
But the problem is that onWritePossible
method is being invoked by the same thread which ran doGet
. Shouldn't it have been different ?