Atom Feed SITE FEED   ADD TO GOOGLE READER

Properties should be stateless to avoid memory leaks

In the latest rev of beansbinding, the AbstractProperty class is stateful. This means that when you add a listener to an object, the property independently remembers both.

For example, suppose your code uses databinding in a dialog:
  private static final Property textFieldTextProperty
= new BeanProperty<JTextField,String>("text");
private static final Property customerNameProperty
= new BeanProperty<Customer,String>("name");

public JDialog createDialog() {
JTextField textField = new JTextField();
Customer customer = new Customer();
Binding customerNameBinding = new Binding<JTextField,String,Customer,String>(
textField, textFieldTextProperty, customer, customerNameProperty);
customerNameBinding.bind();
...
}
After the dialog has been dismissed, the form and its data should fall out-of-scope and get garbage collected. But they don't! Since the textFieldTextProperty field is static and holds a reference to the dialog, the dialog remains in memory until the application exits. This invisible memory leak exists because the addPropertyStateListener method has a hidden side effect.

In this case, the solution is to save a reference to the customerNameBinding and to unbind() it upon dialog closing. Alternately, recreating new Property objects every time the dialog is created will avoid the problem.

Perhaps instead, beansbinding will make Properties stateless.