I don't understand the "this-escape" warning under this context

David Alayachew davidalayachew at gmail.com
Sat Sep 30 03:22:09 UTC 2023


Hello Compiler Dev Team,

I have the following code example.

```java

package Paint;

import javax.swing.*;

public class GUI
{

   private final JFrame frame;

   public GUI()
   {

      this.frame = new JFrame();

      this.frame.add(this.createBottomPanel());

   }

   private final JPanel createBottomPanel()
   {

      final JButton save = new JButton();

      save
         .addActionListener
         (
            actionEvent ->
            {

               this.toString();

            }

         )
         ;

      return null;

   }

}
```

This is the compile command that I used.

```
javac -Xlint:all GUI.java
```

When I compile, I get the following warning.

```
GUI.java:16: warning: [this-escape] possible 'this' escape before subclass
is fully initialized
      this.frame.add(this.createBottomPanel());
                                           ^
GUI.java:28: warning: [this-escape] previous possible 'this' escape happens
here via invocation
            actionEvent ->
            ^
2 warnings
```

Can someone help me understand the what, why, and how of this warning? I
don't understand it at all.

I am pretty sure I understand the basic premise of "this-escape" -- a
not-fully-initialized object (this) can "escape" from its constructor
before completing initialization, usually causing bugs and security
vulnerabilities.

A good example of this is a constructor calling an overridable method. If a
subclass overrides that method, it may expose the state or perform
behaviour that it is not prepared to perform at that time, amongst other
things.

But I struggle to follow that logic for my example. Could someone walk me
through this?

Thank you for your time and help!
David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20230929/f0385aa4/attachment-0001.htm>


More information about the compiler-dev mailing list