Search code examples
javaoopstaticclassloaderpermgen

Can we ever have two copies of an Static field in JAVA


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 ?


Solution

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