Search code examples
javastaticinitializationstatic-initialization

Static final field initialized multiple times


Imagine a java project containing 2 applications. For each of them: a class with a main method to start the app, let's say Main1 and Main2. Both apps are using a shared Service class containing a final static field :

public class Main1 {

    public static void main(String[] args) throws InterruptedException {
        for (int i =0;i<3;i++){
            System.out.println("I'm application number 1. Time =" + Service.time);
            sleep(1000);
        }
    }
}
public class Main2 {

    public static void main(String[] args) throws InterruptedException {
        for (int i =0;i<3;i++){
            System.out.println("I'm application number 2. Time =" + Service.time);
            sleep(1000);
        }
    }
}

public class Service {
    public final static LocalDateTime time = LocalDateTime.now();
}

I was somehow surprised about the output. It seems that Main1 and Main2 have each there own version of Service :

I'm application number 1. Time =2020-07-13T17:04:55.155497300
I'm application number 1. Time =2020-07-13T17:04:55.155497300
I'm application number 1. Time =2020-07-13T17:04:55.155497300

I'm application number 2. Time =2020-07-13T17:04:58.800497300
I'm application number 2. Time =2020-07-13T17:04:58.800497300
I'm application number 2. Time =2020-07-13T17:04:58.800497300

I repeated the experience with the class Service being used by 2 threads. The output was different: time was initialized only once. I'm a bit struggling to understand this. Can anyone helps me understand what happennings behind the scenes?


Solution

  • Main1 and Main2 are completely separate processes on a system level, and separate JVMs. Threads run in the same JVM, that's why the value is the same.

    For 2 JVMs to see the same value, that value would need to be somewhere outside - network, disc, windows registry, anything, but outside.

    For behaviour that you expected you would need a lot stronger mechanisms than a simple static (for example Hazelcast).