JAL-1953 2.11.2 with Archeopteryx!
[jalview.git] / test / jalview / gui / FreeUpMemoryTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import static org.testng.Assert.assertNotNull;
24 import static org.testng.Assert.assertTrue;
25
26 import java.awt.event.MouseEvent;
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.PrintStream;
30
31 import org.testng.annotations.BeforeClass;
32 import org.testng.annotations.Test;
33
34 import jalview.analysis.AlignmentGenerator;
35 import jalview.bin.Cache;
36 import jalview.bin.Jalview;
37 import jalview.datamodel.AlignmentI;
38 import jalview.datamodel.SequenceGroup;
39 import jalview.io.DataSourceType;
40 import jalview.io.FileLoader;
41 import junit.extensions.PA;
42
43 /**
44  * Provides a simple test that memory is released when all windows are closed.
45  * <ul>
46  * <li>generates a reasonably large alignment and loads it</li>
47  * <li>performs various operations on the alignment</li>
48  * <li>closes all windows</li>
49  * <li>requests garbage collection</li>
50  * <li>asserts that the remaining memory footprint (heap usage) is 'not large'
51  * </li>
52  * </ul>
53  * If the test fails, this means that reference(s) to large object(s) have
54  * failed to be garbage collected. In this case:
55  * <ul>
56  * <li>set a breakpoint just before the test assertion in
57  * {@code checkUsedMemory}</li>
58  * <li>if the test fails intermittently, make this breakpoint conditional on
59  * {@code usedMemory > expectedMax}</li>
60  * <li>run the test to this point (and check that it is about to fail i.e.
61  * {@code usedMemory > expectedMax})</li>
62  * <li>use <a href="https://visualvm.github.io/">visualvm</a> to obtain a heap
63  * dump from the suspended process (and kill the test or let it fail)</li>
64  * <li>inspect the heap dump using visualvm for large objects and their
65  * referers</li>
66  * <li>Tips:</li>
67  * <ul>
68  * <li>Perform GC from the Monitor view in visualvm before requesting the heap
69  * dump - test failure might be simply a delay to GC</li>
70  * <li>View 'Objects' and filter classes to {@code jalview}. Sort columns by
71  * Count, or Size, and look for anything suspicious. For example, if the object
72  * count for {@code Sequence} is non-zero (it shouldn't be), pick any instance,
73  * and follow the chain of {@code references} to find which class(es) still hold
74  * references to sequence objects</li>
75  * <li>If this chain is impracticably long, re-run the test with a smaller
76  * alignment (set width=100, height=10 in {@code generateAlignment()}), to
77  * capture a heap which is qualitatively the same, but much smaller, so easier
78  * to analyse; note this requires an unconditional breakpoint</li>
79  * </ul>
80  * </ul>
81  * <p>
82  * <h2>Fixing memory leaks</h2>
83  * <p>
84  * Experience shows that often a reference is retained (directly or indirectly)
85  * by a Swing (or related) component (for example a {@code MouseListener} or
86  * {@code ActionListener}). There are two possible approaches to fixing:
87  * <ul>
88  * <li>Purist: ensure that all listeners and similar objects are removed when no
89  * longer needed. May be difficult, to achieve and to maintain as code
90  * changes.</li>
91  * <li>Pragmatic: null references to potentially large objects from Jalview
92  * application classes when no longer needed, typically when a panel is closed.
93  * This ensures that even if the JVM keeps a reference to a panel or viewport,
94  * it does not retain a large heap footprint. This is the approach taken in, for
95  * example, {@code AlignmentPanel.closePanel()} and
96  * {@code AnnotationPanel.dispose()}.</li>
97  * <li>Adjust code if necessary; for example an {@code ActionListener} should
98  * act on {@code av.getAlignment()} and not directly on {@code alignment}, as
99  * the latter pattern could leave persistent references to the alignment</li>
100  * </ul>
101  * Add code to 'null unused large object references' until the test passes. For
102  * a final sanity check, capture the heap dump for a passing test, and satisfy
103  * yourself that only 'small' or 'harmless' {@code jalview} object instances
104  * (such as enums or singletons) are left in the heap.
105  */
106 public class FreeUpMemoryTest
107 {
108   private static final int ONE_MB = 1000 * 1000;
109
110   /*
111    * maximum retained heap usage (in MB) for a passing test
112    */
113   private static int MAX_RESIDUAL_HEAP = 45;
114
115   /**
116    * Configure (read-only) Jalview property settings for test
117    */
118   @BeforeClass(alwaysRun = true)
119   public void setUp()
120   {
121     Jalview.main(
122             new String[]
123             { "-nonews", "-props", "test/jalview/testProps.jvprops" });
124     String True = Boolean.TRUE.toString();
125     Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS", True);
126     Cache.applicationProperties.setProperty("SHOW_QUALITY", True);
127     Cache.applicationProperties.setProperty("SHOW_CONSERVATION", True);
128     Cache.applicationProperties.setProperty("SHOW_OCCUPANCY", True);
129     Cache.applicationProperties.setProperty("SHOW_IDENTITY", True);
130   }
131
132   @Test(groups = "Memory")
133   public void testFreeMemoryOnClose() throws IOException
134   {
135     File f = generateAlignment();
136     f.deleteOnExit();
137
138     doStuffInJalview(f);
139
140     Desktop.instance.closeAll_actionPerformed(null);
141
142     checkUsedMemory(MAX_RESIDUAL_HEAP);
143   }
144
145   /**
146    * Returns the current total used memory (available memory - free memory),
147    * rounded down to the nearest MB
148    * 
149    * @return
150    */
151   private static int getUsedMemory()
152   {
153     long availableMemory = Runtime.getRuntime().totalMemory();
154     long freeMemory = Runtime.getRuntime().freeMemory();
155     long usedMemory = availableMemory - freeMemory;
156
157     return (int) (usedMemory / ONE_MB);
158   }
159
160   /**
161    * Requests garbage collection and then checks whether remaining memory in use
162    * is less than the expected value (in Megabytes)
163    * 
164    * @param expectedMax
165    */
166   protected void checkUsedMemory(int expectedMax)
167   {
168     /*
169      * request garbage collection and wait for it to run (up to 3 times);
170      * NB there is no guarantee when, or whether, it will do so
171      */
172     long usedMemory = 0L;
173     Long minUsedMemory = null;
174     int gcCount = 0;
175     while (gcCount < 3)
176     {
177       gcCount++;
178       System.gc();
179       waitFor(1500);
180       usedMemory = getUsedMemory();
181       if (minUsedMemory == null || usedMemory < minUsedMemory)
182       {
183         minUsedMemory = usedMemory;
184       }
185       if (usedMemory < expectedMax)
186       {
187         break;
188       }
189     }
190
191     /*
192      * if this assertion fails (reproducibly!)
193      * - set a breakpoint here, conditional on (usedMemory > expectedMax)
194      * - run VisualVM to inspect the heap usage, and run GC from VisualVM to check 
195      *   it is not simply delayed garbage collection causing the test failure 
196      * - take a heap dump and identify large objects in the heap and their referers
197      * - fix code as necessary to null the references on close
198      */
199     System.out.println("(Minimum) Used memory after " + gcCount
200             + " call(s) to gc() = " + minUsedMemory + "MB (should be <="
201             + expectedMax + ")");
202     assertTrue(usedMemory <= expectedMax, String.format(
203             "Used memory %d should be less than %d (Recommend running test manually to verify)",
204             usedMemory, expectedMax));
205   }
206
207   /**
208    * Loads an alignment from file and exercises various operations in Jalview
209    * 
210    * @param f
211    */
212   protected void doStuffInJalview(File f)
213   {
214     /*
215      * load alignment, wait for consensus and other threads to complete
216      */
217     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(f.getPath(),
218             DataSourceType.FILE);
219     while (af.getViewport().isCalcInProgress())
220     {
221       waitFor(200);
222     }
223
224     /*
225      * open an Overview window
226      */
227     af.overviewMenuItem_actionPerformed(null);
228     assertNotNull(af.alignPanel.overviewPanel);
229
230     /*
231      * exercise the pop-up menu in the Overview Panel (JAL-2864)
232      */
233     Object[] args = new Object[] {
234         new MouseEvent(af, 0, 0, 0, 0, 0, 1, true) };
235     PA.invokeMethod(af.alignPanel.overviewPanel,
236             "showPopupMenu(java.awt.event.MouseEvent)", args);
237
238     /*
239      * set a selection group - potential memory leak if it retains
240      * a reference to the alignment
241      */
242     SequenceGroup sg = new SequenceGroup();
243     sg.setStartRes(0);
244     sg.setEndRes(100);
245     AlignmentI al = af.viewport.getAlignment();
246     for (int i = 0; i < al.getHeight(); i++)
247     {
248       sg.addSequence(al.getSequenceAt(i), false);
249     }
250     af.viewport.setSelectionGroup(sg);
251
252     /*
253      * compute Tree and PCA (on all sequences, 100 columns)
254      */
255     af.openTreePcaDialog();
256     CalculationChooser dialog = af.alignPanel.getCalculationDialog();
257     dialog.openPcaPanel("BLOSUM62", dialog.getSimilarityParameters(true));
258     try
259     {
260       dialog.createTree("BLOSUM62", dialog.getSimilarityParameters(false));
261     } catch (IOException e)
262     {
263       // TODO Auto-generated catch block
264       e.printStackTrace();
265     }
266
267     /*
268      * wait until Tree and PCA have been computed
269      */
270     while (af.viewport.getCurrentTree() == null
271             || dialog.getPcaPanel().isWorking())
272     {
273       waitFor(10);
274     }
275
276     /*
277      * give Swing time to add the PCA panel (?!?)
278      */
279     waitFor(100);
280   }
281
282   /**
283    * Wait for waitMs miliseconds
284    * 
285    * @param waitMs
286    */
287   protected void waitFor(int waitMs)
288   {
289     try
290     {
291       Thread.sleep(waitMs);
292     } catch (InterruptedException e)
293     {
294     }
295   }
296
297   /**
298    * Generates an alignment and saves it in a temporary file, to be loaded by
299    * Jalview. We use a peptide alignment (so Conservation and Quality are
300    * calculated), which is wide enough to ensure Consensus, Conservation and
301    * Occupancy have a significant memory footprint (if not removed from the
302    * heap).
303    * 
304    * @return
305    * @throws IOException
306    */
307   private File generateAlignment() throws IOException
308   {
309     File f = File.createTempFile("MemoryTest", "fa");
310     PrintStream ps = new PrintStream(f);
311     AlignmentGenerator ag = new AlignmentGenerator(false, ps);
312     int width = 100000;
313     int height = 100;
314     ag.generate(width, height, 0, 10, 15);
315     ps.close();
316     return f;
317   }
318 }