Clean JavaFX property listeners and bindings (memory leaks)

后端 未结 2 573
北荒
北荒 2020-12-12 16:29

I haven\'t found a simple answer for these two questions:

  1. do I have to remove a listener before deleting the property instance (the listener is not used any

2条回答
  •  臣服心动
    2020-12-12 17:13

    I completely agree with the case 1 answer, but the case 2 is a bit more tricky. The bool.unbind() call is necessary. If ommitted, it does cause a small memory leak.

    If you run the following loop, the application will eventually run out of memory.

    BooleanProperty p1 = new SimpleBooleanProperty();
    while(true) {
        BooleanProperty p2 = new SimpleBooleanProperty();
        p2.bind(p1)
    }
    

    The BooleanPropertyBase, intenally, does not use a real WeakListener (an implementation of the WeakListener interface), it is using a half-baked solution. All the "p2" instances get eventually garbage-collected, but a listener holding an empty WeakReference remains in the memory forever for each "p2". The same holds for all properties, not only BooleanPropertyBase. It's explained here in detail, and they say it is fixed in Java 9.

    In most cases, you do not notice this memory leak, because it leaves only a few dozen bytes for every binding that has not been unbound. But in some cases it caused me real trouble. An good example are table cells of a table that gets frequently updated. The cells then re-bind to different properties all the time, and these left-overs in the memory accumulate quickly.

提交回复
热议问题