我有一个简单的JavaFX应用程序,可以打开浏览器并显示谷歌页面。在退出Application并释放所有对象后,我可以看到在调用GC之后,诸如Scene,Stage,WebView和WebEngine之类的JavaFX对象在堆内存中是活动的。 我可以使用JProfiler和其他Profiler工具看到这个对象。
这是我的测试代码:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TestMemoryLeak
{
private Stage anotherStage;
private Application app;
public void initFrame()
{
JButton btnStart = new JButton("Start");
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread javaFxThread = new Thread(new Runnable() {
@Override
public void run() {
new JFXPanel();
Platform.runLater(new Runnable() {
@Override
public void run() {
try
{
app = MyApplication.class.newInstance();
anotherStage = new Stage();
app.start(anotherStage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
});
javaFxThread.setDaemon(true);
javaFxThread.start();
}
};
btnStart.addActionListener(a1);
JButton btnStop = new JButton("Stop");
ActionListener a2 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Platform.runLater(new Runnable() {
public void run() {
try
{
anotherStage.close();
anotherStage = null;
app.stop();
Platform.exit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
};
btnStop.addActionListener(a2);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(btnStart);
frame.getContentPane().add(btnStop);
frame.setTitle("Memory Leak");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
new TestMemoryLeak().initFrame();
}
}
我的JavaFX应用程序:
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class MyApplication extends Application {
private Scene scene;
@Override
public void start(Stage stage)
{
// create the scene
stage.setTitle("Web View");
scene = new Scene(new Browser(), 800, 600, Color.web("#666970"));
stage.setScene(scene);
stage.show();
}
}
class Browser extends Region {
WebView browser = new WebView();
WebEngine engine = browser.getEngine();
public Browser() {
// load the web page
engine.load("http://www.google.es");
//add the web view to the scene
getChildren().add(browser);
}
@Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
}
}
要测试应用程序,请单击“开始”按钮以显示Google网页,单击“停止”按钮以停止应用程序,运行Profiler工具,然后调用gc,JavaFX类仍处于活动状态。
我使用的是java版本" 1.7.0_51"和Windows 8.1
我的代码中有什么问题吗?或者这是正常的行为?
感谢您的回复。