This article is a case study to simplify the IntelliJ Platform to introduce the IntelliJ Platform in the disposer.
In fact, the SDK documentation already has a more detailed description of this: Disposer and Disposable, before we get started, it might be a good idea to take a look here.
Scene Description
I have modelled a scenario here. There is a ToolWindow layout as follows,Here we use the UI Inspector to analyse the layout:
A rootPanel with BorderLayout, top (North) is a Toolbar, center (Center) is a JPanel. Click ➕ will add a random code snippet to Center’s JPanel.
The scenario, as above, is a very simple ToolWindow with very simple functionality.
Memory leak
Here is the key part of the code snippet:
and
Here we just create the Editor object, but we don’t clean up the memory it occupies when the program exits.
When closing the IDE, relevant exception messages are displayed (Of course, this information is also displayed in the idea.log):
According to the error log, we can know that it is because the created Editor object is not released when the application is closed and there is a risk of memory overflow.
Solving
Ok, now we already know where the problem is, the following we solve the problem, the solution is also simple, just need to close the IDE, release in this object can be.
First, make MainPanel implement the Disposable interface and override the dispose() method. Then after creating editor, register Disposer with parent this to indicate that the editor will be destroyed when this is disposed.
In addition, since in this case the components are all based on Content, we register the disposer for content as MainPanel
The source code for ContentImpl.java looks like this, and you can see that when content is destroyed, it calls Disposer.dispose(myDisposer); to destroy the set myDisposer, which is the MainPanel above.
So now the whole process is as follows:
So, when content is closed, the editor object is also destroyed.