14

I have this classes:

public class User {

    public static final NonRegisteredUser NON_REG_USER = new NonRegisteredUser();

    //...

    public static class NonRegisteredUser extends User {
        //...
    }

}

And code inspector is detecting this warning:

Referencing subclass NonRegisteredUser from superclass User initializer might lead to class loading deadlock

What does it mean exactly?

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Héctor
  • 24,444
  • 35
  • 132
  • 243

2 Answers2

13

The deadlock can only occur if you have 2 threads and one starts to load User and one starts to load NonRegisteredUser. There are synchronizations in place that will cause a deadlock, but then it requires separate threads. If the loading happens in a single thread, there is no deadlock as the thread owns both locks.

Hence the might in the message. However deadlocks usually do tend to require a specific environment, so there's nothing weird about that.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

Class loader begins loading User.

Static members are init first, in order of appearance. So the class loader sees the NonRegisteredUser class, and tries loading the User class for its initialization.

Next, class loader begins loading User.

Static members are init first, in order of appearance. So the class loader sees the NonRegisteredUser class, and tries loading the User class for its initialization.

Next, class loader begins loading User.

Static members are init first, in order of appearance. So the class loader sees the NonRegisteredUser class, and tries loading the User class for its initialization...

Vaiden
  • 15,728
  • 7
  • 61
  • 91
  • 3
    Thank you. So, why is that code working? Does it make sense? – Héctor Dec 28 '17 at 14:49
  • It's probably working because what I just said is not 100% correct. The compiler build a single init process for the class, so the JVM won't blindely iterates over it over and over during runtime. There is probably some optimization in play here, that fixes this kind of issues. – Vaiden Dec 28 '17 at 14:53
  • @Héctor That's a nice question, what happens when you try to use the `User.NON_REG_USER ` attribute or initialize the `User.NonRegisteredUser ` class ? – giannis christofakis Dec 28 '17 at 14:54
  • @giannischristofakis It works fine. But I'm working on android with several threads, the error may occur so I'm gonna decouple the classes – Héctor Dec 28 '17 at 14:57