Search code examples
javamemory-leaksgephi

how to kill object in org.openide.util.Lookup


I use gephi to draw the social graph.But,it use singleton to create class ProjectController.

@ServiceProvider(service = ProjectController.class)
public class ProjectControllerImpl implements ProjectController {

private enum EventType {

    INITIALIZE, SELECT, UNSELECT, CLOSE, DISABLE
};
//Data
private final ProjectsImpl projects = new ProjectsImpl();
private final List<WorkspaceListener> listeners;
private WorkspaceImpl temporaryOpeningWorkspace;

public ProjectControllerImpl() {

    //Listeners
    listeners = new ArrayList<WorkspaceListener>();
    listeners.addAll(Lookup.getDefault().lookupAll(WorkspaceListener.class));

    registerNetbeansPropertyEditors();
}

And we can get this class through the netbeans api:

ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);

You can see it has a List in this class.When you create a object from this singleton,it will add the list.It make memory leak,I want to kill the object in org.openide.util.Lookup,how can I do?


Solution

  • The code of the ProjectControllerImpl class you linked to also contains a method removeWorkspaceListener(), which you could use to unregister single listeners when they are not needed any more (assuming you know these listeners and that they can be removed).

    You could, of course, use your own ProjectController implementation that handles the listeners in a different way:

    • You could store instances of WeakReference<WorkspaceListener> instead of strong references to WorkspaceListeners if you do not want your ProjectControllerImpl instance to prevent the WorkspaceListeners to be garbage collected. (This implies that a strong reference to each listener needs to be stored somewhere else as long as the listener instance should live.)
    • Alternatively, do not store the WorkspaceListeners in your ProjectControllerImpl at all, but fetch them via lookupAll() when you actually need them.