使用 request.getSession() 作为锁定对象? [英] Using request.getSession() as a locking object?
问题描述
我有一些获取和设置会话属性的 Java 代码:
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);
}
}
推荐答案
使用您无法控制的锁通常是不受欢迎的.锁的范围应尽可能紧,因为会话或多或少是一个全局对象,它不符合要求.尝试使用 java.util.concurrent.locks 打包并将其作用于您的类.
It is generally frowned upon to use a lock that you have no control over. A lock should be scoped as tightly as possible and since the session is more or less a global object, it does not fit the bill. Try to use a separate lock from the java.util.concurrent.locks package and scope it to your class.
这篇关于使用 request.getSession() 作为锁定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!