Bug 66272

Summary: AsyncContextListener.onStartAsync is called before listener can be set
Product: Tomcat 9 Reporter: Alex <a701440>
Component: CatalinaAssignee: Tomcat Developers Mailing List <dev>
Status: RESOLVED INVALID    
Severity: normal    
Priority: P2    
Version: 9.0.65   
Target Milestone: -----   
Hardware: PC   
OS: Mac OS X 10.1   

Description Alex 2022-09-21 18:38:23 UTC
There is currently no way to have the AsyncContextListener.onStartAsync callback invoked. In order to set the AsyncContextListener on the AsyncContext you need to have an instance of the AsyncContext. You can get it by calling request.startAsync, this method immediately calls onStartAsync on the listener before the listener could be set.

        AsyncContextListener listener = new AsyncContextListener();
        AsyncContext asyncContext = request.startAsync(); // calls onStartAsync before listener could be set
        asyncContext.addListener(listener);
Comment 1 Mark Thomas 2022-09-21 20:52:19 UTC
AsyncListener is not designed to work that way.

See the Servlet spec and/or Javadoc.

The Tomcat Javadoc for the Servlet API is even more explicit:
https://tomcat.apache.org/tomcat-10.1-doc/servletapi/jakarta/servlet/AsyncListener.html#onStartAsync(jakarta.servlet.AsyncEvent)