Search code examples
javaeffective-java

about inline the call from effective_java book


i have a question in effective_java this book, what's mean of the 'modern Java virtual machine (JVM) implementations are almost certain to inline the call to the static factory method.' i don't understand 'inline the call to the static factory method'

Quote:

The main advantage of the public field approach is that the declarations make it clear that the class is a singleton: the public static field is final, so it will always contain the same object reference. There is no longer any performance advantage to the public field approach: modern Java virtual machine (JVM) implementations are almost certain to inline the call to the static factory method


Solution

  • The "public field approach" is (taken from the book "Effective Java" By Josh Bloch):

    // Singleton with public final field
    public class Elvis {
        public static final Elvis Elvis = new Elvis();
        private Elvis() { ... }
    
        public void leaveTheBuilding() { ... }
    }
    

    While the approach you're referring to in the quote is the static factory:

    // Singleton with static factory
    public class Elvis {
        private static final Elvis INSTANCE = new Elvis();
        private Elvis() { ... }
        public static Elvis getInstance() { return INSTANCE; }
    
        public void leaveTheBuilding() { ... }
    }
    

    And the quote you mentioned explains that the "performance penalty" for the static factory approach (because we're calling a method getInstance instead of using the field directly via: Elvis.INSTANCE) no longer exist (or, very low chance that it does) since the compiler is smart enough to inline the call in the compiled bytecode, so the performance of both approaches is similar while the second approach is better since it provides encapsulation.