0

I have a big action that takes 50 seconds to process. But, at the same time, I have another action that could be processed on the server (by clicking on a link).

However, if my second action try to access session's attributes put by my first action, they are note available until the end of the first action.

This is my big action:

public String bigAction() {
    HttpSession session = request.getSession();
    synchronized (session) {
        for(int i = 0 ; i < 100000 ; ++i)
             session.setAttribute("foo_"+i, "bar");
        }
    return SUCCESS;
}

And this is my smaller action:

public String smallAction() {
    HttpSession session = request.getSession();
    synchronized (session) {
        session.getAttribute("foo_1", "bar");
    }
    return SUCCESS;
}
First  action: -----------------------------------------------

Second action:  ---      --              ---  -        ---

So, in this example, my second action needs session's attributes created by the first action, but, actually, they don't exist.

How may I synchronize my session?

Tiroc
  • 15
  • 5
Florent06
  • 1,008
  • 2
  • 10
  • 29

2 Answers2

2

As per Servlet spec:

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 threadsafe manner. The Developer has the responsibility for threadsafe 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.

This is safe:

request.getSession().setAttribute("bar", "foo");

This is not guaranteed to be safe:

HttpSession session = request.getSession();
synchronized (session) {
   String value = (String) session.getAttribute("bar");
}

Moreover , the locks will work if on the same object , don't rely on request.getSession() returning same object. There is nothing in the Servlet specification that says a HttpServletSession instance can't be recreated as a facade object every time it is requested.

Read Java theory and practice: Are all stateful Web applications broken? and How HttpSession is not thread safe.

One of the approach is defined here , Java-synchronizing-on-transient-id.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • I tried to follow the tutorial, regarding the explanations above. I tried to do so, but, I have the same problem. I made a static reference to an IdMutexProvider but session's id is different in both case. – Florent06 Jul 15 '13 at 14:38
0

Changes for today:

I am using Struts 2 so I implemented SessionAware because I read it could be a good solution. But this is the same.

Florent06
  • 1,008
  • 2
  • 10
  • 29