2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import static org.testng.Assert.assertNotNull;
24 import static org.testng.Assert.assertTrue;
26 import java.awt.event.MouseEvent;
28 import java.io.IOException;
29 import java.io.PrintStream;
31 import org.testng.annotations.BeforeClass;
32 import org.testng.annotations.Test;
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;
44 * Provides a simple test that memory is released when all windows are closed.
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'
53 * If the test fails, this means that reference(s) to large object(s) have
54 * failed to be garbage collected. In this case:
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
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>
82 * <h2>Fixing memory leaks</h2>
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:
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
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>
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.
106 public class FreeUpMemoryTest
108 private static final int ONE_MB = 1000 * 1000;
111 * maximum retained heap usage (in MB) for a passing test
113 private static int MAX_RESIDUAL_HEAP = 45;
116 * Configure (read-only) Jalview property settings for test
118 @BeforeClass(alwaysRun = true)
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);
132 @Test(groups = "Memory")
133 public void testFreeMemoryOnClose() throws IOException
135 File f = generateAlignment();
140 Desktop.instance.closeAll_actionPerformed(null);
142 checkUsedMemory(MAX_RESIDUAL_HEAP);
146 * Returns the current total used memory (available memory - free memory),
147 * rounded down to the nearest MB
151 private static int getUsedMemory()
153 long availableMemory = Runtime.getRuntime().totalMemory();
154 long freeMemory = Runtime.getRuntime().freeMemory();
155 long usedMemory = availableMemory - freeMemory;
157 return (int) (usedMemory / ONE_MB);
161 * Requests garbage collection and then checks whether remaining memory in use
162 * is less than the expected value (in Megabytes)
166 protected void checkUsedMemory(int expectedMax)
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
172 long usedMemory = 0L;
173 Long minUsedMemory = null;
180 usedMemory = getUsedMemory();
181 if (minUsedMemory == null || usedMemory < minUsedMemory)
183 minUsedMemory = usedMemory;
185 if (usedMemory < expectedMax)
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
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));
208 * Loads an alignment from file and exercises various operations in Jalview
212 protected void doStuffInJalview(File f)
215 * load alignment, wait for consensus and other threads to complete
217 AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(f.getPath(),
218 DataSourceType.FILE);
219 while (af.getViewport().isCalcInProgress())
225 * open an Overview window
227 af.overviewMenuItem_actionPerformed(null);
228 assertNotNull(af.alignPanel.overviewPanel);
231 * exercise the pop-up menu in the Overview Panel (JAL-2864)
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);
239 * set a selection group - potential memory leak if it retains
240 * a reference to the alignment
242 SequenceGroup sg = new SequenceGroup();
245 AlignmentI al = af.viewport.getAlignment();
246 for (int i = 0; i < al.getHeight(); i++)
248 sg.addSequence(al.getSequenceAt(i), false);
250 af.viewport.setSelectionGroup(sg);
253 * compute Tree and PCA (on all sequences, 100 columns)
255 af.openTreePcaDialog();
256 CalculationChooser dialog = af.alignPanel.getCalculationDialog();
257 dialog.openPcaPanel("BLOSUM62", dialog.getSimilarityParameters(true));
258 dialog.openTreePanel("BLOSUM62", dialog.getSimilarityParameters(false));
261 * wait until Tree and PCA have been computed
263 while (af.viewport.getCurrentTree() == null
264 || dialog.getPcaPanel().isWorking())
270 * give Swing time to add the PCA panel (?!?)
276 * Wait for waitMs miliseconds
280 protected void waitFor(int waitMs)
284 Thread.sleep(waitMs);
285 } catch (InterruptedException e)
291 * Generates an alignment and saves it in a temporary file, to be loaded by
292 * Jalview. We use a peptide alignment (so Conservation and Quality are
293 * calculated), which is wide enough to ensure Consensus, Conservation and
294 * Occupancy have a significant memory footprint (if not removed from the
298 * @throws IOException
300 private File generateAlignment() throws IOException
302 File f = File.createTempFile("MemoryTest", "fa");
303 PrintStream ps = new PrintStream(f);
304 AlignmentGenerator ag = new AlignmentGenerator(false, ps);
307 ag.generate(width, height, 0, 10, 15);