简体   繁体   中英

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.

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).

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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