2016-02-26 83 views
0

此代码导致NetBeans分析器无法看到的内存泄漏。 Windows上的泄漏并没有那么糟糕,并且似乎平稳,但是在运行时绝对会杀死Linux机器的内存。如果我注释掉标签上的setText方法,则内存不会泄漏。如果我打印到控制台而不是将文本发送到标签,则不会发生泄漏。这个Java程序为什么导致内存泄漏?

我认为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

你确定它实际上是在泄漏内存,而不是仅仅使用一切可用的内存?除非必须,否则JVM通常不会清理垃圾。 – resueman

+0

无限循环不能好... – Reimeus

+0

@Reimeus:在生产中,这段代码是使用执行程序服务和自行调用的runnable运行的。我试图削减和简化程序,使错误更容易找到。 –

回答

0

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