Singleton in a cluster environment

royjayd
royjayd used Ask the Experts™
on
hi guys

If there are two cache servers connected with a cluster and if i am using a singleton design pattern to create a singleton object, is it possible
that instance 1 is created in one server and instance 2 is created in another server ?

thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
If you create a singleton, you're going to get one instance per JVM (or possibly per classloader if you're doing something fancy).

So on two different servers (which implies 2 different JVMs) you will get two different instances.

If you're saying these instances are being stored in a replicating cache then it would depend on the design of the caching software as to how it would handle this.

Doug

Author

Commented:
thanks

One the contrary if i have one weblogic applicaiton server and i have 2 WAR projects deployed in it. Both the WAR projects have the same singleton java class. Will the singleton instance be in each of the WAR project or just one instance be used across both the WARS?

thanks
I think if you have 2 WAR files you will end up with 2 instances of the singleton.  That's because the goal is for each WAR to be completely isolated from the other - they shouldn't be able to communicate or affect each other.  If they shared the same singletons that wouldn't be the case.

Doug
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Author

Commented:
Alright,  but don't the two WARs share the same jvm if they are both deployed in the same application server?

Thx
They do share the same JVM but the container (weblogic in your case) will use 2 separate class loaders - so each set of classes is loaded independently of each other.  Which in turn leads to the multiple singletons.

Doug

Author

Commented:
Aahh, its clear now. So there are two aspects to it,
Class loaders and
The JVM itself

thanks.

Author

Commented:
So I guess each (WAR)web-project will have its own class loader which will
Load the classes of that web-project when application server starts?
Yes that's right.  It allows the container to keep each project separate - which is usually the correct behavior.

Doug

Author

Commented:
thanks
can you please help me with this question
http://www.experts-exchange.com/Programming/Languages/Java/Q_27734431.html

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial