4

When i ran the following program it just hung forever and seems to me it is because of deadlock.

From my understanding I

  • The static field isInitialized is initially set to false.
  • Then the main thread creates a background thread whose run method sets isInitializedto true.
  • The main thread starts the background thread and waits for it to complete by calling join.
  • Once the background thread has completed, there can be no doubt that isInitialized must ha been set to True.

But when i ran the program, found that it prints nothing; it just hangs!

public class Test {
    private static boolean isInitialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                isInitialized = true;
            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {

        }
    }

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

Can some one help me understand this behavior,Is there any deadlock if so why ?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • I added some printlns; and to be precise: it is hanging in *run*; doing the assignment. It doesn't hang without the join call. Funny. – GhostCat May 08 '17 at 07:12

0 Answers0