2

Consider algorithm:

  1. a new attribute is added to the session session.setAttribute("myObject", new Object);
  2. HttpSessionAttributeListener#attributeAdded is invoked
  3. code after session.setAttribute

Does HttpSessionAttributeListener#attributeAdded block session.setAttribute or listener code invokes async?

Cherry
  • 31,309
  • 66
  • 224
  • 364

2 Answers2

3

Listener is invoked in the same thread as set|get|removeAttribute() is invoked.

So, the only race condition may occur when setAttribute() is invoked in another thread. Given that the average servlet container uses a single thread per HTTP connection (and thus not necessarily per HTTP request when HTTP 1.1 keep-alive is on), then this race condition may occur when the enduser spawns two completely separate browser instances (not windows/tabs) and copies the session cookie from the one to the other and then simultaneously fires a request from both clients on that session triggering the setAttribute() method in server.

This is however not an usual real world case. Moreover, the container will all by itself worry about threadsafety of accessing the HttpSession instance. This is specified in chapter 7.7.1 of Servlet specification (emphasis mine):

7.7.1 Threading Issues

Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a thread safe manner. The Developer has the responsibility for thread safe access to the attribute objects themselves. This will protect the attribute collection inside the HttpSession object from concurrent access, eliminating the opportunity for an application to cause that collection to become corrupted.

So your only concern is the threasafety of the attribute itself. E.g. if it's an ArrayList, and you worry about its threadsafety, you'd likely want to wrap it in Collections#synchronizedList().

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Its a SYNC Process . I just made one sample program.

JSP Code :

<%
session.setAttribute("ID","12324");
session.setAttribute("ID2","656565");
%>

Listener Code of attributeAdded() Method :

String attributeName = event.getName();
        Object attributeValue = event.getValue();
        System.out.println("Attribute added : " + attributeName + " : " + attributeValue);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("After Sleep : "+attributeName);

Output :

Attribute added : ID : 12324
After Sleep : ID
Attribute added : ID2 : 656565
After Sleep : ID2

So you can see that only after printing "After Sleep " for the first id its going to add second id in the session

Rahman
  • 3,755
  • 3
  • 26
  • 43