1

It seems that "static block + new thread + static variable" would cause program freeze?

public class HelloWorld{
    private static String str  = "Hi";
    
    static{
        Thread thread = new Thread(new Runnable(){
            public void run(){
                System.out.println(HelloWorld.str);
            }
        });
        
        thread.start();
        try{
            thread.join();
        }
        catch (InterruptedException e) {
                e.printStackTrace();
        }
        
        System.out.println("Static block end");
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

The code above would cause program freeze.

While changing static variable to final static variable, like this

public class HelloWorld{
    private final static String str  = "Hi";
    
    static{
        Thread thread = new Thread(new Runnable(){
            public void run(){
                System.out.println(HelloWorld.str);
            }
        });
        
        thread.start();
        try{
            thread.join();
        }
        catch (InterruptedException e) {
                e.printStackTrace();
        }
        
        System.out.println("Static block end");
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

or call from original thread, like this

public class HelloWorld{
    private static String str  = "Hi";
    static{
        System.out.println(HelloWorld.str);
        System.out.println("Static block end");   
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

would both work.

Not really sure why "static block + new thread + static variable" would cause program freeze?

charlie lin
  • 107
  • 1
  • 1
  • 5
  • 1
    The output of `jstack` will help your understanding. – Jeff Holt May 27 '22 at 13:04
  • @JeffHolt What's the reason the new thread is in Object.wait() state? – charlie lin May 27 '22 at 15:10
  • I'm pretty sure it's waiting for something that can only happen after the static block finishes. – Jeff Holt May 27 '22 at 15:27
  • Program runs to completion if I comment out the `join()` call. I can only _guess_ that the new thread is not allowed to access `str` until `str` has been fully initialized, and becaiuse `str` is assignable, and because a `static` block exists, `str` is not considered to be fully initialized until the main thread has completed execution of the `static` block. I don't actually know how those things are _supposed_ to interact though. – Solomon Slow May 27 '22 at 15:51
  • Yeah that makes sense. One strange thing is that accessing static variable from main thread inside static block never put main thread in wait state. Seems like two threads have different criteria on what is fully initialized. – charlie lin May 27 '22 at 16:13

0 Answers0