javacompiler-warningsjava-21

Why does 'this-escape' warning trigger when calling final methods from the superclass


Java 21 introduces a new this-escape warning which warns against situations where a constructor is calling a method which can be overriden by a subclass. This is a potentially dangerous situation because the overriden method might now depend on fields in the subclass which are not yet initialized because the superclass constructor isn't finished.

I don't understand why the warning is triggering when a class calls a final method which is declared in one of it's own parents.

Here's an example:

package org.example;

public class A {
    public final int getNumber() {
        return 10;
    }
}

public class B extends A {
    public B(){
        getNumber(); // Compiler warns here:
                     // warning: [this-escape] possible 'this' escape 
                     // before subclass is fully initialized
    }
}

Is there a way that B can be extended which would cause a problem? If getNumber() was not final then a subclass of B could potentially break itself, but I don't see the error condition here.

A potential problem is if the superclass method calls another non-final method. Assuming that that not the case, is there still an error condition?

I can't tell if this warning is a false positive, or a very esoteric error I don't understand.


Solution

  • As pointed out in the comments, it has been specified

    Note, when determining if a 'this' escape is possible, the compiler makes no assumptions about code outside of the current compilation unit. It doesn't look outside of the current source file to see what might actually happen when a method is invoked. It does follow method and constructors within the current compilation unit, and applies a simplified union-of-all-possible-branches data flow analysis to see where 'this' could end up.

    The reason is, as also mentioned in the comments, if A is not part of the compilation unit, it could be changed and recompiled independently, so that getNumber()’s implementation calls overridable methods at runtime.

    There is not even a guaranty that getNumber() will be final at runtime. As the specification says:

    Changing a method that is declared final to no longer be declared final does not break compatibility with pre-existing binaries.

    Even the opposite applies, as long as there is no method actually overriding the method then turned into final. Or, in other words, for method invocations, it doesn’t matter whether the target method is final or not.