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 TestStatic class in java from the command line twice.
javaw -cp ... scripts.TestStatic > 1.txt
javaw -cp ... scripts.TestStatic > 2.txt
I expected the first and second execution to interfere, and eventually get the value for Static.CPT == 200, because I thought the JVM would only load after the Static class. This does not seem to be the case. Although I like it, I am wondering if this example is enough to conclude that the JVM completely shares the outputs. In fact, when I read my output, the hash code 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
...
@19f953d split between two performances.
I searched for in-depth explanations for the static keyword, but found nothing about these issues. Can someone explain or give a good pointer?