Lion
Lion

Reputation: 19037

Deadlock caused while creating a Thread in a static block in Java

I was just trying to create a Thread in a static block in Java that caused a deadlock to occur. The code snippet is as follows.

package deadlock;

final public class Main
{
    static int value;

    static
    {
        final Thread t = new Thread()
        {
            @Override
            public void run()
            {
                value = 1;
            }
        };

        t.start();
        System.out.println("Deadlock detected");

        try
        {
            t.join();
        }
        catch (InterruptedException e)
        {
            System.out.println(e.getMessage());
        }
        System.out.println("Released");
    }

    public static void main(String...args)
    {
        //Java stuff goes here.
    }
}

It just displays Deadlock detected on the console and hangs. I guess the reason for the deadlock to occur may be that the static block is loaded first before the main() method is invoked. Can you see the exact reason for the deadlock in the above code snippet?

Upvotes: 1

Views: 385

Answers (3)

Ingo Kegel
Ingo Kegel

Reputation: 48070

Technically, you don't call this a deadlock. "Deadlock" implies that there is a monitor contention of some sort.

What you are doing has the same effect as calling

synchronized (Main.class) {
    try {
        Main.class.wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

as the first thing in your main method. You are in a wait state from which you are never woken up.

Upvotes: 0

kochobay
kochobay

Reputation: 392

if you comment out

    try
    {
        t.join();
    }
    catch (InterruptedException e)
    {
        System.out.println(e.getMessage());
    }

deadlock will not occur...Your thread will run after class load.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692023

In order for the thread to be able to set the static value, the class must be loaded. In order for the class to be loaded, the thread must end (so that the static block completes). That's probably why you have a deadlock.

Upvotes: 5

Related Questions