gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:12 25 4
gpt4 key购买 nike

此代码会导致 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 驱动程序 (Nouveau) 有问题。在为我的系统 (NVidia Quadro K2200) 安装正确的图形驱动程序后,内存泄漏消失了。

关于java - 为什么这个Java程序会导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com