Alex Rivera | Logout

Using request.getSession() as a locking object?

Asked 2009-11-30T15:50:58.720
11

I have some java code that gets and sets a session attribute:

Object obj = session.getAttribute(TEST_ATTR);
if (obj==null) {
  obj = new MyObject();
  session.setAttribute(obj);
}

In order to make this code thread-safe, I'd like to wrap it in a synchronized block. But what do I use as the locking object? Does it make sense to use the session?

synchronized (session) {
  Object obj = session.getAttribute(TEST_ATTR);
  if (obj==null) {
    obj = new MyObject();
    session.setAttribute(obj);
  }
}
Edit
Report

1 Answer

1

I had the same problem and didn't want to scope it to my class because the creation of my object might take a second and stall threads of others sessions where the object was created already. I didn't want to use the session object of the request to synchronize on because the application server implementation might return a differen session facade in different requests and synchronizing on different objects simply doesn't work. So I choose to put an object on the session to use as a lock and use the double check idiom to ensure the lock is created only once. Synchronizing in the scope of MyObject is not a problem any more because creating an object is quite fast.

Object lock = session.getAttribute("SessionLock");
if (lock == null) {
  synchronized (MyObject.class) {
    lock = session.getAttribute("SessionLock");
    if(lock == null) {
      lock = new Object();
      session.setAttribute("SessionLock", lock);
    }
  }
}
synchronized (lock) {
  Object obj = session.getAttribute(TEST_ATTR);
  if (obj==null) {
    obj = new MyObject();
    session.setAttribute(obj);
  }
}
answered 2013-06-27T13:04:34.350

Your Answer