Note that there are some explanatory texts on larger screens.

plurals
  1. POJava : static fields behaviour in different executions
    text
    copied!<p>I have this class : </p> <pre><code>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); } } </code></pre> <p>Now I run the class TestStatic in java from the command line, twice.</p> <pre><code>javaw -cp ... scripts.TestStatic &gt; 1.txt javaw -cp ... scripts.TestStatic &gt; 2.txt </code></pre> <p>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 :</p> <p>From 1.txt :</p> <pre><code>... 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 ... </code></pre> <p>From 2.txt : </p> <pre><code>... 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 ... </code></pre> <p>The <code>@19f953d</code> is shared among the two executions. </p> <p>I googled for deep explanations on static keyword but did not find anything about these issues. Could someone explain or give a nice pointer ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload