Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to deal with Memory Leaks, that are caused by Binding

cshMay 25 2012 — edited Jun 20 2012
Hi, I recently noticed (huge?) memory leaks in my application and suspect bindings to be the cause of all the evil.

I made a little test case, which confirms my suspicion:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TestAppMemoryLeak extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        VBox root = new VBox();

        Button button = null;

        for (int i = 0; i < 100000; i++) {
            button = new Button();
            button.textProperty().bind(text);
            button.textProperty().unbind(); // if you don't call this, you can notice the increased memory of the java process.
        }


        root.getChildren().add(button);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    private StringProperty text = new SimpleStringProperty("test");
}
Now the problem is, HOW can I know, when a variable is no longer needed or overwritten by a new instance.

Just an example:

I have a ListView with a Cell Factory. In the updateItem method, I add a ContextMenu. The textProperty of each MenuItem is bound to a kind of global property, like in the example above. I have to do it in the updateItem method, since the ContextMenu differs depending on the item.

So every time the updateItem method is called a new ContextMenu is created, which binds some properties, but the old context menus remain in memory.

I guess there could be many more example.

How can I deal with it?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 18 2012
Added on May 25 2012
17 comments
16,743 views