KAY_YAK KAY_YAK - 26 days ago 8
Java Question

If I modify a static variable of a class does it get shared by previous instance of the class?

If I modify a static variable of a class does it get shared by previous instance of the class or only the new instance of the class.

I was just doing RMI and I have a class with static variables which I register to RMI registry. If I update the static variable by calling the RMI object it gets updated but if I update it by classname then check the value of the variable from the RMI object it gives me the old value.

Answer

If class A has a static variable s, then all instances of A in a given JVM will share that static variable. The JLS guarantees this.

Possible explanations for what you are seeing include:

  • You have managed to load class A multiple times in the JVM, using different classloaders. That will give you different A classes, as far as the type system is concerned, and each one will have different static variables.
  • You are actually talking to instances of A in a different JVM in the "by RMI" and "by classname". cases. The classes A in the different JVMs do not share static variables.
  • Various problems with your edit / build / deploy / run cycle.
Comments