简体   繁体   English

JavaFX addEventListener在父级上发生内存泄漏

[英]JavaFX addEventListener Memory Leak on Grand Parent

Why would the anonymous inner class not be released here, causing a memory leak? 为什么不在这里释放匿名内部类,从而导致内存泄漏? This happens for FX 2.2.1. 对于FX 2.2.1,会发生这种情况。

anchorPane.getParent().getParent().lookup("#grandParentButton").addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent e) {
        if (e.getCode() == KeyCode.ENTER) {
            someButtonInsideAnchorPane.requestFocus();
            e.consume();
        }
    }
});

Why would this below on the other hand be garbage collected? 另一方面,为什么下面要进行垃圾收集呢?

button1InsideAnchorPane.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent e) {
        if (e.getCode() == KeyCode.ENTER) {
            button2InsideAnchorPane.requestFocus();
            e.consume();
        }
    }
});

An an inner class always holds a strong ref to its outer class and is only gced if the outer one is not referenced any more. 内部类始终对其外部类具有强引用,并且仅当不再引用外部类时才给予内部引用。 Make it a static inner class and you don't have the problem! 使其成为静态内部类,就没有问题了!

The first answer is wrong. 第一个答案是错误的。 It's true that "An an inner class always holds a strong ref to its outer class", but then it goes the other way round. 的确,“一个内部类总是对其外部类拥有强大的引用”,但随后却相反。 Actually, the outer class can't be collected as long as the inner is alive. 实际上,只要内部类还活着,就无法收集外部类。

The reason for the instance not being collected as its registering as listener. 实例未注册为侦听器而未收集该实例的原因。 The registrar typically holds a strong reference to the listener, so the instance can't be collected (no idea about FX). 注册服务商通常对侦听器有很强的引用,因此无法收集实例(不了解FX)。

The only explanation for the different behavior is that each object was registered with a different component. 对于不同行为的唯一解释是,每个对象都向不同的组件注册。 One of them has got collected and the other hasn't. 其中一个已经收集,而另一个则没有。 No idea why, maybe one of them belonged to a dialog? 不知道为什么,也许其中一个属于对话?

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

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