Using request.getSession() as a locking object?

后端 未结 7 990
面向向阳花
面向向阳花 2020-12-11 02:18

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

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


        
7条回答
  •  忘掉有多难
    2020-12-11 03:09

    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);
      }
    }
    

提交回复
热议问题