3 import static org.testng.Assert.assertNotNull;
4 import static org.testng.Assert.assertTrue;
6 import java.awt.event.MouseEvent;
8 import java.io.IOException;
9 import java.io.PrintStream;
11 import org.testng.annotations.BeforeClass;
12 import org.testng.annotations.Test;
14 import jalview.analysis.AlignmentGenerator;
15 import jalview.bin.Cache;
16 import jalview.bin.Jalview;
17 import jalview.datamodel.AlignmentI;
18 import jalview.datamodel.SequenceGroup;
19 import jalview.io.DataSourceType;
20 import jalview.io.FileLoader;
21 import junit.extensions.PA;
24 * Provides a simple test that memory is released when all windows are closed.
26 * <li>generates a reasonably large alignment and loads it</li>
27 * <li>performs various operations on the alignment</li>
28 * <li>closes all windows</li>
29 * <li>requests garbage collection</li>
30 * <li>asserts that the remaining memory footprint (heap usage) is 'not large'
33 * If the test fails, this means that reference(s) to large object(s) have
34 * failed to be garbage collected. In this case:
36 * <li>set a breakpoint just before the test assertion in
37 * {@code checkUsedMemory}</li>
38 * <li>if the test fails intermittently, make this breakpoint conditional on
39 * {@code usedMemory > expectedMax}</li>
40 * <li>run the test to this point (and check that it is about to fail i.e.
41 * {@code usedMemory > expectedMax})</li>
42 * <li>use <a href="https://visualvm.github.io/">visualvm</a> to obtain a heap
43 * dump from the suspended process (and kill the test or let it fail)</li>
44 * <li>inspect the heap dump using visualvm for large objects and their
48 * <li>Perform GC from the Monitor view in visualvm before requesting the heap
49 * dump - test failure might be simply a delay to GC</li>
50 * <li>View 'Objects' and filter classes to {@code jalview}. Sort columns by
51 * Count, or Size, and look for anything suspicious. For example, if the object
52 * count for {@code Sequence} is non-zero (it shouldn't be), pick any instance,
53 * and follow the chain of {@code references} to find which class(es) still hold
54 * references to sequence objects</li>
55 * <li>If this chain is impracticably long, re-run the test with a smaller
56 * alignment (set width=100, height=10 in {@code generateAlignment()}), to
57 * capture a heap which is qualitatively the same, but much smaller, so easier
58 * to analyse; note this requires an unconditional breakpoint</li>
62 * <h2>Fixing memory leaks</h2>
64 * Experience shows that often a reference is retained (directly or indirectly)
65 * by a Swing (or related) component (for example a {@code MouseListener} or
66 * {@code ActionListener}). There are two possible approaches to fixing:
68 * <li>Purist: ensure that all listeners and similar objects are removed when no
69 * longer needed. May be difficult, to achieve and to maintain as code
71 * <li>Pragmatic: null references to potentially large objects from Jalview
72 * application classes when no longer needed, typically when a panel is closed.
73 * This ensures that even if the JVM keeps a reference to a panel or viewport,
74 * it does not retain a large heap footprint. This is the approach taken in, for
75 * example, {@code AlignmentPanel.closePanel()} and
76 * {@code AnnotationPanel.dispose()}.</li>
77 * <li>Adjust code if necessary; for example an {@code ActionListener} should
78 * act on {@code av.getAlignment()} and not directly on {@code alignment}, as
79 * the latter pattern could leave persistent references to the alignment</li>
81 * Add code to 'null unused large object references' until the test passes. For
82 * a final sanity check, capture the heap dump for a passing test, and satisfy
83 * yourself that only 'small' or 'harmless' {@code jalview} object instances
84 * (such as enums or singletons) are left in the heap.
86 public class FreeUpMemoryTest
88 private static final int ONE_MB = 1000 * 1000;
91 * maximum retained heap usage (in MB) for a passing test
93 private static int MAX_RESIDUAL_HEAP = 45;
96 * Configure (read-only) Jalview property settings for test
98 @BeforeClass(alwaysRun = true)
103 { "-nonews", "-props", "test/jalview/testProps.jvprops" });
104 String True = Boolean.TRUE.toString();
105 Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS", True);
106 Cache.applicationProperties.setProperty("SHOW_QUALITY", True);
107 Cache.applicationProperties.setProperty("SHOW_CONSERVATION", True);
108 Cache.applicationProperties.setProperty("SHOW_OCCUPANCY", True);
109 Cache.applicationProperties.setProperty("SHOW_IDENTITY", True);
112 @Test(groups = "Memory")
113 public void testFreeMemoryOnClose() throws IOException
115 File f = generateAlignment();
120 Desktop.instance.closeAll_actionPerformed(null);
122 checkUsedMemory(MAX_RESIDUAL_HEAP);
126 * Returns the current total used memory (available memory - free memory),
127 * rounded down to the nearest MB
131 private static int getUsedMemory()
133 long availableMemory = Runtime.getRuntime().totalMemory();
134 long freeMemory = Runtime.getRuntime().freeMemory();
135 long usedMemory = availableMemory - freeMemory;
137 return (int) (usedMemory / ONE_MB);
141 * Requests garbage collection and then checks whether remaining memory in use
142 * is less than the expected value (in Megabytes)
146 protected void checkUsedMemory(int expectedMax)
149 * request garbage collection and wait for it to run (up to 3 times);
150 * NB there is no guarantee when, or whether, it will do so
152 long usedMemory = 0L;
153 Long minUsedMemory = null;
160 usedMemory = getUsedMemory();
161 if (minUsedMemory == null || usedMemory < minUsedMemory)
163 minUsedMemory = usedMemory;
165 if (usedMemory < expectedMax)
172 * if this assertion fails (reproducibly!)
173 * - set a breakpoint here, conditional on (usedMemory > expectedMax)
174 * - run VisualVM to inspect the heap usage, and run GC from VisualVM to check
175 * it is not simply delayed garbage collection causing the test failure
176 * - take a heap dump and identify large objects in the heap and their referers
177 * - fix code as necessary to null the references on close
179 System.out.println("(Minimum) Used memory after " + gcCount
180 + " call(s) to gc() = " + minUsedMemory + "MB (should be <="
181 + expectedMax + ")");
182 assertTrue(usedMemory <= expectedMax, String.format(
183 "Used memory %d should be less than %d (Recommend running test manually to verify)",
184 usedMemory, expectedMax));
188 * Loads an alignment from file and exercises various operations in Jalview
192 protected void doStuffInJalview(File f)
195 * load alignment, wait for consensus and other threads to complete
197 AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(f.getPath(),
198 DataSourceType.FILE);
199 while (af.getViewport().isCalcInProgress())
205 * open an Overview window
207 af.overviewMenuItem_actionPerformed(null);
208 assertNotNull(af.alignPanel.overviewPanel);
211 * exercise the pop-up menu in the Overview Panel (JAL-2864)
213 Object[] args = new Object[] {
214 new MouseEvent(af, 0, 0, 0, 0, 0, 1, true) };
215 PA.invokeMethod(af.alignPanel.overviewPanel,
216 "showPopupMenu(java.awt.event.MouseEvent)", args);
219 * set a selection group - potential memory leak if it retains
220 * a reference to the alignment
222 SequenceGroup sg = new SequenceGroup();
225 AlignmentI al = af.viewport.getAlignment();
226 for (int i = 0; i < al.getHeight(); i++)
228 sg.addSequence(al.getSequenceAt(i), false);
230 af.viewport.setSelectionGroup(sg);
233 * compute Tree and PCA (on all sequences, 100 columns)
235 af.openTreePcaDialog();
236 CalculationChooser dialog = af.alignPanel.getCalculationDialog();
237 dialog.openPcaPanel("BLOSUM62", dialog.getSimilarityParameters(true));
238 dialog.openTreePanel("BLOSUM62", dialog.getSimilarityParameters(false));
241 * wait until Tree and PCA have been computed
243 while (af.viewport.getCurrentTree() == null
244 || dialog.getPcaPanel().isWorking())
250 * give Swing time to add the PCA panel (?!?)
256 * Wait for waitMs miliseconds
260 protected void waitFor(int waitMs)
264 Thread.sleep(waitMs);
265 } catch (InterruptedException e)
271 * Generates an alignment and saves it in a temporary file, to be loaded by
272 * Jalview. We use a peptide alignment (so Conservation and Quality are
273 * calculated), which is wide enough to ensure Consensus, Conservation and
274 * Occupancy have a significant memory footprint (if not removed from the
278 * @throws IOException
280 private File generateAlignment() throws IOException
282 File f = File.createTempFile("MemoryTest", "fa");
283 PrintStream ps = new PrintStream(f);
284 AlignmentGenerator ag = new AlignmentGenerator(false, ps);
287 ag.generate(width, height, 0, 10, 15);