6

Static variables have only instance (that is they are part of the class). ex: Math.pi

Is there any way there could be multiple instances of static variables? I heard there is something related to Classloaders?

1 Answer 1

15

If you find that you need multiple instances of a static variable, this is a strong indication that you should not be using static variables in the first place.

Yes, if the same class is loaded in different class loaders, then each copy of the class will have its own statics. However, the only code that can refer statically to those statics will be classes loaded by the same class loader. And of course, that code will only (statically) see the statics in one copy of the class. So you probably haven't achieved a lot.

Rather than messing around with classloaders, you should be refactoring your code to turn the static variables into instance variables.

Sign up to request clarification or add additional context in comments.

4 Comments

@satish - so I haven't convinced you that it is a bad idea?
the point was not about bad-idea, but trying to understand the idea behind the multiple-classloaders. do point me to any tutorials or examples if you come across any. Thanks for the great answer :-)
Sometimes one has to use a library whose classes puke all over the static region making it impossible to get multiple stable instances. If I'm force to use such a library a custom ClassLoader is just a longer stick to poke it with. (:
I think you (and maybe other people) would be better off in the long run if you concentrated your effort on getting that crap library fixed. Fix it or replace it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.