Search code examples
jsf-2cdihttpsession

Is it thread unsafe for a @SessionScoped bean to maintain a reference to its HttpSession?


Taking a look at the unrelated portion of this answer to another question, although I understand why the references to request and response are threadunsafe in the question's example, why is it threadunsafe for a SessionScoped bean to reference the HttpSession to which it is bound?

@SessionScoped
public class SessionManager {
    HttpSession session = null;
    ...
    @PostConstruct void initialize() {
        this.session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    }

    private void onLogin(@Observes @LoggedIn User user) {

        // (1) housekeeping stuff

        // (2) destroy older, duplicate login session, if user did not previously 
        //     logout, in which case it would be really handy to have a reference
        //     to HttpSession. 

    }
}

Solution

  • While implementing the example I sketched out, above (see OP), I realized that maintaining a reference to a session is not good because it is indeed thread unsafe. It is smelly code.

    I was surprised to see that not only did the old session get invalidated but the current session was destroyed by the container as well! So the user was logged out in both browsers. Later, I came across this Websphere best practices documentation, which, although I am not using Websphere, helped me realize that caching the session is not good practice at all:

    Avoid trying to save and reuse the HttpSession object outside of each servlet or JSP file.

    The HttpSession object is a function of the HttpRequest (you can get it only through the req.getSession method), and a copy of it is valid only for the life of the service method of the servlet or JSP file. You cannot cache the HttpSession object and refer to it outside the scope of a servlet or JSP file.

    There is no need to cache HttpSession; one can instead cache the session ID and when a duplicate session is discovered simply add the previous duplicate session's ID to Set<String> invalidatedLoginSessionIds. Then refactor the application such that immediately upon receiving a request from the old session invalidate the old session and redirect the old browser to the appropriate facelet. If no such request is received the old session will simply time out and be destroyed anyway, so no worries there.