Charles Morin
Charles Morin

Reputation: 1447

Concurrent HTTP Session is returning wrong user

I am experiencing a quite weird problem. When two users are logging at the exact same time, one of them is detected as the other.

    locale = new Locale(getLocale(request).getLanguage(), getLocale(request).getCountry());


    strRemoteUser = WebTools.getUserIdWithoutDomainName(request.getRemoteUser()).toUpperCase();

    logger.info("[MYAPP] User " + strRemoteUser + " is logging in");

    logger.info("[MYAPP] Creating session for : " + strRemoteUser);

    HttpSession session = request.getSession(false);

    if (session != null) {

        session.invalidate();
        session = request.getSession();
    }       

    logger.info("[MYAPP] User in session is : " + strRemoteUser);             

What I get is the following. Let's assume that two users (USR001 and USR002) are logging to the application at the same exact time. They are located in a different location.

Logs:

    2013-05-14 08:19:38,550 INFO  [com.myapp.action.common.LoginAction] [MYAPP] User USR001 is logging in
2013-05-14 08:19:38,551 INFO  [com.myapp.action.common.LoginAction] [MYAPP] Creating session for : USR001
2013-05-14 08:19:38,760 INFO  [com.myapp.action.common.LoginAction] [MYAPP] User USR002 is logging in
2013-05-14 08:19:38,761 INFO  [com.myapp.action.common.LoginAction] [MYAPP] Creating session for : USR002
2013-05-14 08:19:38,834 INFO  [com.myapp.action.common.LoginAction] [MYAPP] User in session is : USR002
2013-05-14 08:19:39,104 INFO  [com.myapp.action.common.LoginAction] [MYAPP] User in session is : USR002
2013-05-14 08:19:39,425 INFO  [com.myapp.action.common.LoginAction] [MYAPP] Auto Added User USR002
2013-05-14 08:19:39,550 INFO  [com.myapp.action.common.LoginAction] [MYAPP] Setting user in session: USR002 (673)

As you can see, USR002 "wins" the concurrent session creation as USR001 is now recognized as USR002. If USR001 logs out and then log back in, it works properly.

Any thoughts/advice?

Thank you very much for help.

Specs:

Upvotes: 2

Views: 1273

Answers (2)

Victor
Victor

Reputation: 3818

Many developers are missing the fact that Struts 1 uses single instance of Action to serve requests from all sessions, so Actions should be written in concurrent-safe manner, e.g.

  • use only immutable (final) fields
  • use local variables instead of mutable fields
  • be aware of thread-unsafe classes like Calendar, SimpleDateFormat and Matcher

Of course there are many more subtle issues, and there are many resources to learn from (e.g. Java Concurrency in Practice by Brian Goetz).

P.S. Action Class Design Guidelines from the original Apache Struts documentation

Upvotes: 1

happybuddha
happybuddha

Reputation: 1358

I am glad it helped. Here's the comment posted as an answer : These are classic concurrency issues, if we are talking about the same thing. Move the variable into the method and run it again and look at the output.

Upvotes: 1

Related Questions