The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

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.

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

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.

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).