Julien Berthoud
Julien Berthoud

Reputation: 769

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?

Upvotes: 0

Views: 183

Answers (2)

Mafick
Mafick

Reputation: 1170

Yeah of course both programs have their own version of your Service. One time it is the static variable of the first program and another one it is the static variable of the second program.

Service will not have the same memory. And the time difference is just the iterative working of your programs.

If you want to have only 1 Service you can work with the singleton pattern. But this have to be in the same program.

Upvotes: 1

Shadov
Shadov

Reputation: 5592

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

Upvotes: 1

Related Questions