I have a few Servlets which call remote EJB session to manage user’s requests. At a first time I created a new manager in each method this way:
ManagerAdminRemote managerAdmin;
Context jndiContext = new javax.naming.InitialContext();
Object ref = jndiContext.lookup("ManagerAdmin/remote");
managerAdmin = (ManagerAdminRemote) PortableRemoteObject.narrow(ref, ManagerAdminRemote.class);
To avoid this repetition, I implemented the init method like this:
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context jndiContext = new javax.naming.InitialContext();
Object ref = jndiContext.lookup("ManagerAdmin/remote");
managerAdmin = (ManagerAdminRemote) PortableRemoteObject.narrow(ref, ManagerAdminRemote.class);
} catch (NamingException e) {
e.printStackTrace();
}
}
With managerAdmin declared as class attribute.
Session Bean ManagerAdmin is stateless.
I’m using JBoss 5 and I saw that init() is called the first time the Servlet is called. But I also noticed that all the users share the same objects declared as class attribute. So this way, for instance, different users will share the same managerAdmin.
For now I didn’t encounter any problem, but I’m asking: could this sharing bring problems of any kind? Delays? Or, since managers are stateless, is it fine?
Thanks in advance.
You should be fine using stateless services as long as the references to those services are instance variables. Alternatively you could create a
getManagerAdmin()method that handles the lookup for you and thus you wouldn’t have to repeat the lookup code in each method.If you can use Java EE 6 and thus EJB 3.1 you might want to let the container inject the services into the servlet. Note that this only works for local lookups in the same class loading context (normally the same application but it might be the same JVM if the applications are not isolated by the web/application server).