9b212749bca07fda9d9c8704a9234be18ab4faa8
[jalview.git] / test / jalview / gui / FreeUpMemoryTest.java
1 package jalview.gui;
2
3 import static org.testng.Assert.assertEquals;
4 import static org.testng.Assert.assertNotNull;
5 import static org.testng.Assert.assertTrue;
6
7 import jalview.analysis.AlignmentGenerator;
8 import jalview.bin.Cache;
9 import jalview.bin.Jalview;
10 import jalview.datamodel.AlignmentI;
11 import jalview.datamodel.SequenceGroup;
12 import jalview.io.DataSourceType;
13 import jalview.io.FileLoader;
14
15 import java.awt.event.MouseEvent;
16 import java.io.File;
17 import java.io.IOException;
18 import java.io.PrintStream;
19
20 import org.testng.annotations.BeforeClass;
21 import org.testng.annotations.Test;
22
23 import junit.extensions.PA;
24
25 public class FreeUpMemoryTest
26 {
27   private static final int ONE_MB = 1000 * 1000;
28
29   /**
30    * Configure (read-only) Jalview property settings for test
31    */
32   @BeforeClass(alwaysRun = true)
33   public void setUp()
34   {
35     Jalview.main(new String[] { "-nonews", "-props",
36         "test/jalview/testProps.jvprops" });
37     String True = Boolean.TRUE.toString();
38     Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS", True);
39     Cache.applicationProperties.setProperty("SHOW_QUALITY", True);
40     Cache.applicationProperties.setProperty("SHOW_CONSERVATION", True);
41     Cache.applicationProperties.setProperty("SHOW_OCCUPANCY", True);
42     Cache.applicationProperties.setProperty("SHOW_IDENTITY", True);
43   }
44
45   /**
46    * A simple test that memory is released when all windows are closed.
47    * <ul>
48    * <li>generates a reasonably large alignment and loads it</li>
49    * <li>performs various operations on the alignment</li>
50    * <li>closes all windows</li>
51    * <li>requests garbage collection</li>
52    * <li>asserts that the remaining memory footprint (heap usage) is 'not large'
53    * </li>
54    * </ul>
55    * If the test fails, this suggests that a reference to some large object
56    * (perhaps the alignment data, or some annotation / Tree / PCA data) has
57    * failed to be garbage collected. If this is the case, the heap will need to
58    * be inspected manually (suggest using jvisualvm) in order to track down
59    * where large objects are still referenced. The code (for example
60    * AlignmentViewport.dispose()) should then be updated to ensure references to
61    * large objects are set to null when they are no longer required.
62    * 
63    * @throws IOException
64    */
65   @Test(groups = "Memory")
66   public void testFreeMemoryOnClose() throws IOException
67   {
68     File f = generateAlignment();
69     f.deleteOnExit();
70
71     doStuffInJalview(f);
72
73     Desktop.instance.closeAll_actionPerformed(null);
74
75     checkUsedMemory(35L);
76   }
77
78   /**
79    * Requests garbage collection and then checks whether remaining memory in use
80    * is less than the expected value (in Megabytes)
81    * 
82    * @param expectedMax
83    */
84   protected void checkUsedMemory(long expectedMax)
85   {
86     /*
87      * request garbage collection and wait for it to run;
88      * NB there is no guarantee when, or whether, it will do so
89      * wait time depends on JRE/processor, generous allowance here  
90      */
91     System.gc();
92     waitFor(1500);
93
94     /*
95      * a second gc() call should not be necessary - but it is!
96      * the test passes with it, and fails without it
97      */
98     System.gc();
99     waitFor(1500);
100
101     /*
102      * check used memory is 'reasonably low'
103      */
104     long availableMemory = Runtime.getRuntime().totalMemory() / ONE_MB;
105     long freeMemory = Runtime.getRuntime().freeMemory() / ONE_MB;
106     long usedMemory = availableMemory - freeMemory;
107
108     /*
109      * sanity check - fails if any frame was added after
110      * closeAll_actionPerformed
111      */
112     assertEquals(Desktop.instance.getAllFrames().length, 0);
113
114     /*
115      * if this assertion fails
116      * - set a breakpoint here
117      * - run jvisualvm to inspect a heap dump of Jalview
118      * - identify large objects in the heap and their referers
119      * - fix code as necessary to null the references on close
120      */
121     System.out.println("Used memory after gc = " + usedMemory + "MB");
122     assertTrue(usedMemory < expectedMax, String.format(
123             "Used memory %d should be less than %d (Recommend running test manually to verify)",
124             usedMemory,
125             expectedMax));
126   }
127
128   /**
129    * Loads an alignment from file and exercises various operations in Jalview
130    * 
131    * @param f
132    */
133   protected void doStuffInJalview(File f)
134   {
135     /*
136      * load alignment, wait for consensus and other threads to complete
137      */
138     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(f.getPath(),
139             DataSourceType.FILE);
140     while (af.getViewport().isCalcInProgress())
141     {
142       waitFor(200);
143     }
144
145     /*
146      * open an Overview window
147      */
148     af.overviewMenuItem_actionPerformed(null);
149     assertNotNull(af.alignPanel.overviewPanel);
150
151     /*
152      * exercise the pop-up menu in the Overview Panel (JAL-2864)
153      */
154     Object[] args = new Object[] {
155         new MouseEvent(af, 0, 0, 0, 0, 0, 1, true) };
156     PA.invokeMethod(af.alignPanel.overviewPanel,
157             "showPopupMenu(java.awt.event.MouseEvent)", args);
158
159     /*
160      * set a selection group - potential memory leak if it retains
161      * a reference to the alignment
162      */
163     SequenceGroup sg = new SequenceGroup();
164     sg.setStartRes(0);
165     sg.setEndRes(100);
166     AlignmentI al = af.viewport.getAlignment();
167     for (int i = 0; i < al.getHeight(); i++)
168     {
169       sg.addSequence(al.getSequenceAt(i), false);
170     }
171     af.viewport.setSelectionGroup(sg);
172
173     /*
174      * compute Tree and PCA (on all sequences, 100 columns)
175      */
176     af.openTreePcaDialog();
177     CalculationChooser dialog = af.alignPanel.getCalculationDialog();
178     dialog.openPcaPanel("BLOSUM62", dialog.getSimilarityParameters(true));
179     dialog.openTreePanel("BLOSUM62", dialog.getSimilarityParameters(false));
180
181     /*
182      * wait until Tree and PCA have been computed
183      */
184     while (af.viewport.getCurrentTree() == null
185             && dialog.getPcaPanel().isWorking())
186     {
187       waitFor(10);
188     }
189
190     /*
191      * give Swing time to add the PCA panel (?!?)
192      */
193     waitFor(100);
194   }
195
196   /**
197    * Wait for waitMs miliseconds
198    * 
199    * @param waitMs
200    */
201   protected void waitFor(int waitMs)
202   {
203     try
204     {
205       Thread.sleep(waitMs);
206     } catch (InterruptedException e)
207     {
208     }
209   }
210
211   /**
212    * Generates an alignment and saves it in a temporary file, to be loaded by
213    * Jalview. We use a peptide alignment (so Conservation and Quality are
214    * calculated), which is wide enough to ensure Consensus, Conservation and
215    * Occupancy have a significant memory footprint (if not removed from the
216    * heap).
217    * 
218    * @return
219    * @throws IOException
220    */
221   private File generateAlignment() throws IOException
222   {
223     File f = File.createTempFile("MemoryTest", "fa");
224     PrintStream ps = new PrintStream(f);
225     AlignmentGenerator ag = new AlignmentGenerator(false, ps);
226     int width = 100000;
227     int height = 100;
228     ag.generate(width, height, 0, 10, 15);
229     return f;
230   }
231 }