Pergunta

I understand

  1. Static fields belongs/associates to CLASS type
  2. Its used by all Object of that class
  3. If the class is loaded by two different class loader in a same JVM then we can have two copies.

Is there any way/scenario that I can have two copies of my static with different values ?

Foi útil?

Solução

Yes, you can have this case for static final primitives.

Let's consider the following case:

  1. Class A has public static final int SOME_CONSTANT = 1
  2. Class B references A.SOME_CONSTANT
  3. Class A and B are compiled
  4. Class B changes to public static final int SOME_CONSTANT = 2
  5. Class B is re-compiled WITHOUT recompiling class A

If you were to now start a JVM (with A and B on the classpath), the value of the static will be 1 in class A whereas class B will have a value of 2. This is because javac compiles a copy of the value into each .class file. Class B has it's own copy of the static and does not reference class A. To fix this, you MUST recompile class A every time the constant changes in class B (ie do a clean build instead of an incremental build). Note, this problem is only for static final primitives (int, long etc).

Outras dicas

If your class C is loaded by two different class loaders CL1 and CL2,
then there are two instances c1, c2 of java.lang.Class describing your
class C. Then in each one of them (c1, c2) you can have different values
in your static field f (f is defined in C).

Some people even argue that technically these two c1, c2
are different classes as far as the JVM is concerned.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top