javamultithreadingdeadlockstatic-initializer

Can a thread enter a static method before static initialization (class loading) is complete by another thread?


Lets say we have the following classes and two threads t1,t2.

public class A {
        static String str = "abc";

        static {
          B.bMeth();
        }

        static void aMeth() {
            System.out.println("A::meth()");
            str = "abc2";
        }

        static void aSomeMeth() {}
    }

public class B {

        static {
            A.aMeth();
        }

        static void bMmeth() {}
        static void bSomeMeth() {}
    }

Following is the sequence for the deadlock to occur:

1) t1 executes A.aSomeMeth() which acquires lock on class loading for A.

2) t2 executes B.bSomeMeth() which acquires lock on class loading for B.

3) t1 proceeds to execute B.bMeth() and requires lock for B while holding lock of A.

4) t2 proceeds to execute A.aMeth() and requires lock for A while holding lock for B.

This causes a dead lock. But in my case t2 actually enters aMeth() and is blocked while accessing the static member str. So I want to know if its possible for a thread to enter a static method before initialization in special conditions.

In my test runs, t2 was always blocked at A.aMeth() as expected, so could there be any corner cases where it can enter it and be blocked on str, JIT optimizations like method inlineing etc.


Solution

  • No, a class can only be initialized once, by exactly one thread. If another thread accesses the same class, this one will block while initialization completes.