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