In the Proxy object (the object implementing java.lang.reflect.InvocationHandler), I am trying to set an instance variable in the proxied object.
Like the following:
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; } } Is this safe?
EDIT:
Actual code:
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; Edit2: The proxied object is being called from GWT client that calls multiple methods of the same proxied object at the same time. When this happens, I got the session instance field (of proxied class) to be closed and opened in unexpected manner.
SessionFactorywill solve the problem.. correct?