I struggle to find resources on this, and yet, so many of my classes are running into this error when I compile my code on the latest Java (21).
Here is a code example.
public class ThisEscapeExample
{
public Object o;
public ThisEscapeExample()
{
this.overridableMethod();
}
public void overridableMethod()
{
this.o = new Object();
}
}
And here is my compilation command.
javac -Xlint:all ThisEscapeExample.java
ThisEscapeExample.java:9: warning: [this-escape] possible 'this' escape before subclass is fully initialized
this.overridableMethod();
^
1 warning
Here is the JDK Bug System entry that introduces this new warning - https://bugs.openjdk.org/browse/JDK-8299995
Long story short, the
this-escapewarning is to warn you when a subclass may be able to@Overridea method that is also called in the superclass' constructor.This is dangerous because overriding a method that is used in the constructor allows subclass' to unintentionally introduce a bug during a subclass' initialization. What if that method depends on state that has not yet been created because we are still in the super constructor? After all, you cannot do anything in the subclass' constructor before calling the super constructor (for now).
There are a few ways to remedy this.
Only use methods in the constructor that cannot be overridden.
staticmethods.finalmethods.privatemethods.Make the class itself
final.Don't pass in/use
thisto begin with - instead, pass in the particular component ofthisthat you needed.Please note - these rules apply recursively. Meaning, when you call a method in the constructor, not only does that method have to be "not-overridable", but the methods that that method passes
thisinto must ALSO match one of the rules above. If your top-level method is not overridable, but one of the methods inside of it is, and that method hasthisin its scope, then you will receive athis-escapeerror upon compilation. Here is an example.