Object singletons in Servlets/Beans
Hi Everyone,
I am new to Java and I am not sure if there are issues relating to singleton classes in servlets/beans especially in a clustered environment.
Here is a simple example of a hashmap in a singleton class called GlobalModuleInfoList and both a servlet and a bean registers themselves and access it.
This example might be silly, but can someone tell me if it will cause problems in a clustered environment or not.
Thank you
Eric
Code :
@WebServlet("/Example")
public class Example extends HttpServlet {
private static ModuleInfo myInfo = GlobalModuleInfoList.registerModule("Example", "1.0");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
myInfo.incUsageCounter();
}
//....
Code :
@Singleton
@LocalBean
public class MyBean {
private static ModuleInfo myInfo = GlobalModuleInfoList.registerModule("MyBean", "1.0");
//....
Code :
public class GlobalModuleInfoList {
private static HashMap<String, ModuleInfo> modules = new HashMap<String, ModuleInfo>();
public synchronized static ModuleInfo registerModule(String name, String version) {
ModuleInfo m = null; m = modules.get(name);
if (m==null) {m = new ModuleInfo(version, version);modules.put(name, m);}
return m;
}
}
Code :
public class ModuleInfo {
String name;
String version;
int usageCounter;
public ModuleInfo(String name, String version) {this.name=name; this.version=version;}
public synchronized int incUsageCounter() {usageCounter++; return usageCounter;}
}
Re: Object singletons in Servlets/Beans
Depending upon the server environment, different class loaders or JVM's might load the classes - for read/write static variables this creates a problem as different instances of the variables might exist. There may be further problems with data synchronization, if multiple threads attempt to read/write at the same time.
Re: Object singletons in Servlets/Beans
Quote:
Originally Posted by
copeg
Depending upon the server environment, different class loaders or JVM's might load the classes - for read/write static variables this creates a problem as different instances of the variables might exist. There may be further problems with data synchronization, if multiple threads attempt to read/write at the same time.
Thanks for your feedback.
I also found this response from Mike Baranczak that makes the same point.
Quote:
You should generally avoid static variables in Java EE or servlet containers, because the class loading can be a bit tricky - you may wind up with multiple copies when you don't expect it, or you may be sharing a single copy between different applications, or you may be keeping stuff in memory when you redeploy your application. You can make an exception in cases where the variable isn't exposed outside the class, and you don't really care how many copies of it you have (for example, logger objects).