How to understand a java concurrency book example in practice?

Listing 3.15. A class is at risk of failure if it is not properly published.

public class Holder {
 private int n;
 public Holder(int n) { this.n = n; }
 public void assertSanity() {
 if (n != n)
 throw new AssertionError("This statement is false.");
 }
} 

My first question is: why doesn't javac optimize if (n != n)?

Below is my demo for an example

public class TestSync {
    private int n;

    public TestSync(int n) {
        this.n = n;
    }

    public void assertSanity() {
        if(n!=n)
            throw new AssertionError("This statement is false");
    }

    private static TestSync test;
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    if(test == null) test = new TestSync(2);
                    else test = null;
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    if(test != null)
                        try {
                            test.assertSanity();
                        } catch (NullPointerException e) {

                        }
                }
            }
        }).start();
    }
}

And my second question is: did I do it right? Because it is not an exception when I run a demo.

UPDATE

1. Addition to my first question: javap -c TestSync.class

public void assertSanity();
    Code:
       0: aload_0
       1: getfield      #3                  // Field n:I
       4: aload_0
       5: getfield      #3                  // Field n:I
       8: if_icmpeq     21
      11: new           #4                  // class java/lang/AssertionError
      14: dup
      15: ldc           #5                  // String This statement is false
      17: invokespecial #6                  // Method java/lang/AssertionError."<init>":(Ljava/lang/Object;)V
      20: athrow
      21: return

I thought javac would optimize if(n!=n)to if(false)and shorten it.

2. Why am I still adding try{}catch(NullPointerException e)after if(test != null)?

Since I think the field testcan be set by nullanother thread after if(test!=null).

0
source share
1 answer

, javac , . , javac , , . JLS ยง15.28, .

, , , . , n!=n - true - ยน true , . n!=n false, - true .

, , , , , ...

ยน , 0 - , n!=n , 0 .

0

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


All Articles