Assigning an array variable value to itself?

I have this simple piece of code.

class A { static volatile String[] a = new String[9]; public static void main(String[] args) { new Thread() { public void run() { for (int i = 0; i < a.length; i++) { while (a[i] == null); System.out.println(a[i]); } } }.start(); a[0] = "The"; zzz(); a[1] = "quick"; zzz(); a[2] = "brown​"; zzz(); a[3] = "fox"; zzz(); a[4] = "jumped"; zzz(); a[5] = "over"; zzz(); a[6] = "the"; zzz(); a[7] = "lazy"; zzz(); a[8] = "cat"; zzz(); } public static void zzz() { try { Thread.sleep(300); } catch (Exception e) {} a=a; } } 

It outputs what I expect:

 $ javac A.java && java A The quick brown​ fox jumped over the lazy cat 

The strange thing is a=a in zzz() . It doesn't seem to change anything when I take it out. Why is he there?

+4
source share
1 answer

The only reason I can think of is because the person who wrote this code realized that only the array is volatile, but not its contents, and added a = a to ensure that the records executed on the elements of the array are visible.

It seems nothing changes when I take it out.

The fact that it is still running on your machine with your JVM does not mean that it will work on another machine with a different JVM. Theoretically, deleting the operator a = a; can lead to an infinite while loop.


Side note

I would think that the Java Memory Model (JMM) might allow the JVM to ignore this statement, just as synchronized(new Object()) could be ignored.

It seems that this is not the case * :

You may have noticed that I provided a way to get the volatile record above using only arrays: by writing out self-promotion .

* Jeremy Manson is one of the authors of JMM.

+4
source

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


All Articles