Well, then all these setOnXXX() should mention it as well, wouldn't you say?

Perhaps a better solution might be a general purpose tutorial which addresses 
the common pitfalls like memory leaks, and new features like Subscription.

We do have these tutorials for java8 -

https://docs.oracle.com/javase/8/javafx/events-tutorial/events.htm

But since JavaFX has been decoupled from the JDK we don't seem to have anything 
more recent.  I don't know whether this situation is going to change any time 
soon.

-andy


From: Thiago Milczarek Sayão <thiago.sa...@gmail.com>
Date: Thursday, April 18, 2024 at 08:51
To: Andy Goryachev <andy.goryac...@oracle.com>
Cc: openjfx-dev <openjfx-dev@openjdk.org>
Subject: [External] : Re: Possible leak on setOnAction
I was investigating,

It probably should be menuItem.setOnAction(new WeakEventHandler<>(e -> 
stage.toFront()));

But I bet it's a common mistake. Maybe the setOnAction should mention it?



Em qui., 18 de abr. de 2024 às 11:54, Andy Goryachev 
<andy.goryac...@oracle.com<mailto:andy.goryac...@oracle.com>> escreveu:
You are correct - the lambda strongly references `stage` and since it is in 
turn is strongly referenced from the menu item it creates a leak.

The lambda is essentially this:

menuItem.setOnAction(new H(stage));
class $1 implements EventHandler<ActionEvent> {
  private final Stage stage;
  public $1(Stage s) {
    this.stage = s; // holds the reference and causes the leak
  }
  public void handle(ActionEvent ev) {
    stage.toFront();
  }
}

-andy

From: openjfx-dev 
<openjfx-dev-r...@openjdk.org<mailto:openjfx-dev-r...@openjdk.org>> on behalf 
of Thiago Milczarek Sayão 
<thiago.sa...@gmail.com<mailto:thiago.sa...@gmail.com>>
Date: Thursday, April 18, 2024 at 03:42
To: openjfx-dev <openjfx-dev@openjdk.org<mailto:openjfx-dev@openjdk.org>>
Subject: Possible leak on setOnAction
Hi,

I'm pretty sure setOnAction is holding references.

I have a "Open Windows" menu on my application where it lists the Stages opened 
and if you click, it calls stage.toFront():

menuItem.seOnAction(e -> stage.toFront())

I had many crash reports, all OOM. I got the hprof files and analyzed them - 
turns out this was holding references to all closed stages.

To fix it, I call setOnAction(null) when the stage is closed.

I will investigate further and provide an example.

-- Thiago.

Reply via email to