Search code examples
memory-leaksjavafx-2boolean-expression

JavaFX - Methods creating a new BooleanExpression cause memory leaks


I have just noticed that methods not(), and(), or() from both classes BooleanExpression and Bindings create a new BooleanExpression which probably stays in memory even if it does not have any reference.

myBool = new SimpleBooleanProperty();
 for (int i = 0; i < 10000000; i++) {
 myBool.not();
}

Aforementioned code creates about 530 MB which stay in memory until the 'myBool' variable is dereferenced (and cleaned).

Is this a bug or normal behavior? If so, is there any way how to clean the memory without loosing 'myBool' variable?


Solution

  • This is not a bug, when you are invoking not() you are creating a BooleanBinding. This binding is bound to the SimpleBooleanProperty using the listener mechanism. That means that the SimpleBooleanProperty keeps a strong reference on the binding.

    The binding must be "unbound" from the property. The dispose() method does the trick;

    BooleanBinding binding = myBool.not();
    binding.dispose();
    

    Note that the javadoc of this method is not very accurate.