I have this class :
package scripts;
public class TestStatic {
public static void main(String[] args) {
new IncrA().incrStatic();
}
}
class Static {
public static int CPT = 0;
}
class IncrA{
public void incrStatic(){
for (int i:Range.ints(0,100)){
System.out.println("Now with "+this.toString()+" : Static.CPT="+Static.CPT);
Static.CPT++;
try{
Thread.sleep(100);
}
catch(Exception e){
e.printStackTrace();
}
}
System.out.println("Finally for execution of "+this.toString()+" : Static.CPT="+Static.CPT);
}
}
Now I run the class TestStatic in java from the command line, twice.
javaw -cp ... scripts.TestStatic > 1.txt
javaw -cp ... scripts.TestStatic > 2.txt
I was expecting that the first and second executions would interfere, and get a value for Static.CPT == 200 in the end, because I thought the JVM would load only once the Static class. It seems it is not the case. Although I like it, I wonder if this example of mine is enough to conclude that the JVM completely separates exectutions. Actually, when I read my output, the hashCode for my IncrA object is often the same in both executions :
From 1.txt :
...
Now with scripts.IncrA@19f953d : Static.CPT=72
Now with scripts.IncrA@19f953d : Static.CPT=73
Now with scripts.IncrA@19f953d : Static.CPT=74
Now with scripts.IncrA@19f953d : Static.CPT=75
...
From 2.txt :
...
Now with scripts.IncrA@19f953d : Static.CPT=72
Now with scripts.IncrA@19f953d : Static.CPT=73
Now with scripts.IncrA@19f953d : Static.CPT=74
Now with scripts.IncrA@19f953d : Static.CPT=75
...
The @19f953d
is shared among the two executions.
I googled for deep explanations on static keyword but did not find anything about these issues. Could someone explain or give a nice pointer ?