0

As part of exception handling, I want to print data from HTTP session like below:

try{  
    //business logic
} catch(Exception ex){
    String user = session.get("userId"); //get user from HTTP Session.
    log.info("Exception when processign the user "+user); 
}

My question is do I get the correct UserId for which exception occurred since there will be mulitple threads updating the session?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Greg
  • 147
  • 1
  • 5
  • 18

2 Answers2

1

The HttpSession is not shared among clients. So that part is safe already. The remnant depends on your own code as to obtaining and handling the HttpSession instance. If you're for example assinging the HttpSession as an instance variable of an application wide class, like the servlet itself, then it is indeed not thread safe as it might be overridden by another request at the moment you're accessing it.

public class SomeServlet extends HttpServlet {

    private HttpSession session;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        session = request.getSession();

        // ...

        Object object = session.getAttribute("foo"); // Not threadsafe!
    }  

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for the answer. Infact I am using JSF to be specific and trying to get the data in the session map like facesContext.getExternalContext().getSessionMap("userId"). So in the catch block I get the userId for whci exception occured per your answer I believe. – Greg Jan 26 '12 at 19:57
  • The principle stands. As long as you don't assign `FacesContext`, `ExternalContext` or `SessionMap` as an instance variable of a managed bean, then it's safe. The "See also" link is definitely worth a read, also for JSF as it uses Servlet API under the covers. – BalusC Jan 26 '12 at 19:58
0

Session will be unique for each user (if code is according to standard).

Here is sun tutorial on how session works

kosa
  • 65,990
  • 13
  • 130
  • 167