繁体   English   中英

为什么此Java程序会导致内存泄漏?

[英]Why does this Java program cause a memory leak?

此代码导致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){

            }
        }
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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