简体   繁体   中英

Why does this Java program cause a memory leak?

This code causes a memory leak which the NetBeans profiler cannot see. The leak is not that bad on Windows and appears to level out but absolutely kills the memory of a Linux machine when run. If I comment out the setText method on the label the memory is not leaked. If I print out to the console instead of sending the text to the label the leak does not happen.

I think the setText() method is holding onto the old values for some reason.

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

/**
 *
 * @author admin
 */
public class Sandbox {


    Label theLabel;
    boolean isUpdating = false;
    int count = 0;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Sandbox();
    }   

    public Sandbox(){

        new JFXPanel(); // this will prepare JavaFX toolkit and environment
        FlowPane root = new FlowPane(Orientation.VERTICAL);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                Scene scene = new Scene(root, 600, 600);
                Stage stage = new Stage();
                stage.setScene(scene);
                stage.show();
            }
        });

        theLabel = new Label();
        root.getChildren().add(theLabel);

        while(true){
            try{
                count ++;
                if(isUpdating == false){
                    isUpdating = true;
                    Platform.runLater(new Runnable(){
                        public void run(){
                            theLabel.setText("TEST:" + count); //The culprit
                            isUpdating = false;
                        }
                    });
                }
                Thread.sleep(0);
            }catch(InterruptedException ex){

            }
        }
    }
}

It appears that JavaFX has an issue with the default Linux driver (Noveau). After I installed the correct graphics driver for my system (NVidia Quatro K2200) the memory leak went away.

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