有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

linux为什么这个Java程序会导致内存泄漏?

此代码导致NetBeans探查器无法看到的内存泄漏。漏洞在Windows上并没有那么严重,看起来很平稳,但在运行Linux机器时绝对会占用内存。如果我注释掉标签上的setText方法,内存就不会泄漏。如果我打印到控制台而不是将文本发送到标签,则不会发生泄漏

我认为setText()方法出于某种原因保留了旧值

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){

            }
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    JavaFX似乎与默认Linux驱动程序(Noveau)存在问题。在我为我的系统安装了正确的图形驱动程序(NVidia Quatro K2200)后,内存泄漏消失了