【发布时间】:2012-07-19 16:16:42
【问题描述】:
在代理对象(实现java.lang.reflect.InvocationHandler的对象)中,我试图在代理对象中设置一个实例变量。
如下:
public class ServiceProxy implements InvocationHandler {
private final Object proxiedObject;
private ServiceProxy(final Object object) {
this.proxiedObject = object;
}
public static Object newInstance(final Object object) {
return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new ServiceProxy(object));
}
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object result = null;
MyObject mo = new MyObject();
// Is the following safe when the proxiedObject is being acceessed by multiple threads?
final Field sessionField = this.proxiedObject.getClass().getSuperclass().getDeclaredField("mo");
sessionField.setAccessible(true);
sessionField.set(this.object, mo);
result = method.invoke(this.proxiedObject, args);
return result;
}
}
这样安全吗?
编辑:
实际代码:
Object result = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession()
// Is the following save when the proxiedObject is being acceessed by multiple threads?
final Field sessionField = this.proxiedObject.getClass().getSuperclass().getDeclaredField("session");
sessionField.setAccessible(true);
sessionField.set(this.object, session);
result = method.invoke(this.proxiedObject, args);
return result;
编辑2: 代理对象是从同时调用同一代理对象的多个方法的 GWT 客户端调用的。发生这种情况时,我让会话实例字段(代理类)以意想不到的方式关闭和打开。
【问题讨论】:
-
您遇到的实际问题是什么。您在下面暗示了一个“线程问题”,它是什么?
-
我不明白您所说的“以意外方式关闭和打开”是什么意思。其次,如果您暗示您正在从多个线程使用休眠会话,那么您应该知道休眠会话不是线程安全的。
-
线程1打开会话,线程1使用打开会话..然后线程2请求打开会话,如果尚未打开..然后线程1关闭会话..然后线程2尝试使用会话(已关闭),因此这里出现异常......
-
我认为使用
SessionFactory可以解决问题.. 对吗? -
是的,每个线程都应该使用自己的 Session 实例(根据需要使用 SessionFactory 获取 Session 实例)。
标签: java multithreading proxy invocationhandler