我知道关于非静态内部类的内存泄漏的问题已经被问过。我读过的问题是this和this,但我不完全明白我在做什么错。java私有的内部类实例没有被垃圾收集
我的类是如下
public class AddNewProductDialog {
private static AddNewProductDialog dialog;
private TextInputDialog newProductName = new TextInputDialog();
private AddNewProductDialog(){
}
public static AddNewProductDialog getInstance(){
if(dialog == null){
dialog = new AddNewProductDialog();
}
return dialog;
}
/*Helper Class start*/
private class AddNewProductDialogHelper{
private void initializeDialog(){ //---> Prepare a dialog box
newProductName.setTitle("Add New Product");
newProductName.setHeaderText("Note: This product name will be used as bat script file name. Eg. call_<productname>_script");
newProductName.setContentText("Product Name :");
newProductName.getDialogPane().lookupButton(ButtonType.OK).setDisable(true);
/*Something over here*/
newProductName.getEditor().textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
// TODO Auto-generated method stub
if(isInputvalid(newProductName.getEditor().getText())){
newProductName.getDialogPane().lookupButton(ButtonType.OK).setDisable(false);
}
}
});
}
private boolean isInputvalid(String text){
if(text.trim().length() > 0)
return true;
return false;
}
}
/*Helper class end*/
public AddNewProductDialog build(){
new AddNewProductDialogHelper().initializeDialog();
return this;
}
public void show() {
Optional<String> result = newProductName.showAndWait();
if(result.isPresent()){
//----> handle the input
}
}
}
AddNewProductDialog
的(外)类是具有辅助类AddNewProductDialogHelper
一个单独的类。这个辅助类设置的TextInputDialog newProductName
我打电话AddNewProductDialog
类的build
方法,接着show
方法AddNewProductDialog.getInstance().build().show()
每次一个按钮被点击把用户输入的属性。
我想AddNewProductDialogHelper
的实例是做初始化newProductName
dialog box
的问题是,的AddNewProductDialogHelper
的情况下,在堆内存中起球并收集垃圾没有得到后进行垃圾回收。每次我按一下按钮,获取用户输入的是越来越创建一个新的实例,并不断起球最多的按钮被点击
然而,当我评论这个代码块
newProductName.getEditor().textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
// TODO Auto-generated method stub
if(isInputvalid(newProductName.getEditor().getText())){
newProductName.getDialogPane().lookupButton(ButtonType.OK).setDisable(false);
}
}
});
它的工作原理和以前的实例是垃圾收集。 为什么评论此代码块有效?
我使用VisualVM检查我堆转储
'isInputValid'是您的帮助器的方法,然后在侦听器的关闭中。 –