简体   繁体   中英

JavaFX: Stage and Controller lifecycle…memory management

I would like to know what is the lifecycle of stages and controllers created on the fly(not the main one that extends Application), or in other words, any child window spawned from another window. I am concerned about any memory leaks and I just want to make sure I am building memory/resource efficient GUI application. Here is a sample code:

private void addNewAsset(ActionEvent event) {
    AssetController assetController = new AssetController();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("assetchooser.fxml"));
    loader.setController(assetController);

    Stage assetChooserStage = new Stage();
    assetChooserStage.initModality(Modality.WINDOW_MODAL);
    assetChooserStage.initOwner(listviewAssets.getScene().getWindow());
    assetChooserStage.setTitle("Choose Asset(s)");
    try {
        assetChooserStage.setScene(new Scene((Parent)loader.load()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    assetChooserStage.show();
    assetChooserStage.setOnCloseRequest((windowEvent)->{
        //DO STUFF: Get any data
        List<AssetChosenData> listAssets = assetController.getListAssetChosen();

        System.out.println("CLOSING");}
    );
}

As you can see, the method addNewAsset() is executed when the user clicks at a certain button. The method spawns a new Stage using FXMLLoader and using a controller. When this stage gets closed(setOnCloseRequest), I capture the data I want. What happens afterwards? Will the controller(AssetController) and Stage(assetChooserStage), as well as all the Controls and data used by them, be set to null and the GC come by later and dispose of them?

If you don't know specifics, maybe you can point me to an official Java/Oracle documentation that deals with this subject.

Thanks.

This is just the default Java behavior:

You are creating objects and if you no longer keep (strong) references to them, they are being garbage collected.

In your case you are creating objects solely in a local scope (method) and do not store any object otherwise.

When and if the Stage is garbage collected is an implementation detail out of our reach. If you think there is a memory leak, you should probably file an issue in the JavaFX tracker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM