Java – use request Getsession () as the lock object?

I have some java code to get and set a session property:

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

To make this code thread safe, I want to wrap it in synchronized blocks But what do I use as a lock 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);
  }
}

Solution

Usually frown and use locks you can't control The lock should be locked as tightly as possible. Since the session is more or less a global object, it does not comply with the bill Try using a separate lock from Java util. concurrent. Locks the package and ranges it to your class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>