sialcasa / mvvmFX

an Application Framework for implementing the MVVM Pattern with JavaFX
Apache License 2.0
489 stars 105 forks source link

MemoryLeak while using CachedViewModelCellFactory in ListView #603

Open NoaNoob opened 4 years ago

NoaNoob commented 4 years ago

Hi, I'm using a ListView and implemented a DetailView using the CachedViewModelCellFactory. While running the app over a while I noticed that the cache of the CellFactory is not cleared when new Items are loaded and the app is consuming a growing amount of memory. As a workaround I accessed the cache via reflections an cleared it manually:

public class MyFancyView implements Initializable, FxmlView<MyFancyViewModel> {

    @FXML
    ListView<MyResultViewModel> listMyResultViewModels;

    ViewListCellFactory<MyResultViewModel> cellFactory;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

            cellFactory =
                    CachedViewModelCellFactory.createForFxmlView(MyResultView.class);
            listMyResultViewModels.setCellFactory(cellFactory);

     }

   // call this method on demand
    private void clearCellFactoryCache() {

        try {

            Field cache = cellFactory.getClass().getDeclaredField("cache");
            cache.setAccessible(true);
            Map<MyResultViewModel, ViewTuple<MyResultView, MyResultViewModel>> cachedVMs = (HashMap) cache.get(cellFactory);

            cachedVMs.clear();

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}

Is there an alternative way to do this? Maybe a "cachedSetItems(List vms)" Method?