How to access session from async thread

Viewed 784

I need to use some session-scope data in an asynchronous job. The job is run with Spring @Async annotation. To achieve this goal, request attributes are first remembered in a request thread:

currentAttributes = RequestContextHolder.getRequestAttributes();

Then, in a thread running the async job, the request attributes are restored:

RequestContextHolder.setRequestAttributes(currentAttributes);

Almost everything works - session beans are available. However, I cannot access the HttpSession object - to check if the session is still valid. In a session-scoped bean:

@Autowired
transient private HttpSession session;
//...
private boolean isSessionInvalid() {
    try {
        session.getCreationTime();
        return false;
    } catch (IllegalStateException e) {
        return true;
    }
}

The call session.getCreationTime() throws an IllegalStateException, even when the session is still valid:

java.lang.IllegalStateException: The request object has been recycled and is no longer associated with this facade
    at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:904)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at org.springframework.web.context.support.WebApplicationContextUtils$SessionObjectFactory.getObject(WebApplicationContextUtils.java:366)
    at org.springframework.web.context.support.WebApplicationContextUtils$SessionObjectFactory.getObject(WebApplicationContextUtils.java:361)
    at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:307)

What can I do to make the session available from an async job? Or, alternatively, is there any other way to check that the session is still valid?

0 Answers
Related