JavaFX ImageView - Image cleanup

admin

Administrator
Staff member
I would like to ask if anyone knows how JavaFX ImageView handles Images cleanup.
When Image object / memory is free.

Here is situation that causes problems for me:
I have two "tabs" places on my Scene. This are my tabs done with: buttons and switching panes in parent pane. Each tab has its own ImageView. Before I switch pane I null Image on old ImageView and then load new one. I was expecting that after switch tabs old Image from old ImageView would be free but in fact it is not.

To monitor behaviour I was using Java VisualVM tool and I was triggering GC from it. I was also verifiing list of object through HeapDump and I can confirm that event after calling setImage(null) on imageview the old image is still hold inside ImageView and cannot be collected by GC.

I would be very thankful If anyone could suggest my how to trriger ImageView to clear old Images to save memory.

Below is code that shows this problem sutuation:

Code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class IVTestApp extends Application {

    private String img1 = "http://formaciononline.co/wp-content/uploads/2014/05/aprender-a-programar-en-Java.jpg";
    private String img2 = "https://madushan1995.files.wordpress.com/2015/02/java-institute-new-final.png";

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane bp = new BorderPane();

        BorderPane p1 = new BorderPane();
        ImageView iv1 = new ImageView();
        iv1.setPreserveRatio(true);
        iv1.setFitHeight(200);
        iv1.setFitWidth(300);
        p1.setCenter(iv1);

        BorderPane p2 = new BorderPane();
        ImageView iv2 = new ImageView();
        iv2.setPreserveRatio(true);
        iv2.setFitHeight(200);
        iv2.setFitWidth(300);
        p2.setCenter(iv2);

        Button tab1 = new Button("tab1");
        Button tab2 = new Button("tab2");

        tab1.setOnAction(e -> {
            iv2.setImage(null);
            iv1.setImage(new Image(img1));
            bp.setCenter(p1);
        });

        tab2.setOnAction(e -> {
            iv1.setImage(null);
            iv2.setImage(new Image(img2));
            bp.setCenter(p2);
        });

        bp.setLeft(new VBox(tab1, tab2));

        Scene scen = new Scene(bp);
        primaryStage.setScene(scen);
        primaryStage.setWidth(600);
        primaryStage.setHeight(400);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

// NOTE:
My enviroment was composed of: Windows 7 x64bit with Java x86 jdk8u40