-1

Can someone explain to me why the following code prints nothing? When I tried to debug it, the debugger froze on the line t.join();. But in the debugger I saw the message: "program is running".

public class Main_problem1_multithreading {
    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                initialized = true;
            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            throw new AssertionError(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}
Alex
  • 3,111
  • 6
  • 27
  • 43
Anton
  • 5
  • 2

1 Answers1

1

Static initialization takes place when JVM loads a class first time. The thread that loads the class has a lock on Static Initializer , In this case main thread is already holding the lock. Until that lock is released the newly spawned thread cannot access "initialized" variable.

You can clearly see in the image I attached. Thread - 0 is stepping at line 10. Line 10 is where new thread tries to update initialized variable. So this new thread keep waiting for the lock which it never gets and main thread keeps waiting for new thread to join it. Deadlock!! Hope it helps!

package com.test;

public class Test {
    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                initialized = true;
                System.out.println("New Thread" + initialized);
            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("Main Thread" + initialized);
    }
}

enter image description here

vkg
  • 1,839
  • 14
  • 15