Java: behavior of static fields in different executions

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?

+3
4

: static JVM, , CPT 100. . http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html . , , - .

(er) , , Class . JVM , , , . Java , () CPT , .

( JVM ClassLoaders Class , JVM, .)

- Java-, - (, ) . Java, , , (, TCP-). , .

+9

JVM, . "@19f953d" .

+1

JVM, Static. , , JVM.

It is better to avoid using keywords as identifiers (Static), even if they are capitalized.

+1
source

Nothing is saved between JVM calls.

Staticity is generally for all instances of the same class, and not for the JVM.


Even if they start at the same time, it does not matter. They do not communicate, everyone has their own memory.

0
source

Source: https://habr.com/ru/post/1719364/


All Articles