JAL-3120 preserve feature colour/mincolour/maxcolour while modifying,
[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.assertTrue;
5
6 import jalview.analysis.AlignmentGenerator;
7 import jalview.bin.Cache;
8 import jalview.bin.Jalview;
9 import jalview.datamodel.AlignmentI;
10 import jalview.datamodel.SequenceGroup;
11 import jalview.io.DataSourceType;
12 import jalview.io.FileLoader;
13
14 import java.io.File;
15 import java.io.IOException;
16 import java.io.PrintStream;
17
18 import org.testng.annotations.BeforeClass;
19 import org.testng.annotations.Test;
20
21 public class FreeUpMemoryTest
22 {
23   private static final int ONE_MB = 1000 * 1000;
24
25   /**
26    * Configure (read-only) Jalview property settings for test
27    */
28   @BeforeClass(alwaysRun = true)
29   public void setUp()
30   {
31     Jalview.main(new String[] { "-nonews", "-props",
32         "test/jalview/testProps.jvprops" });
33     Cache.applicationProperties.setProperty("SHOW_ANNOTATIONS",
34             Boolean.TRUE.toString());
35     Cache.applicationProperties.setProperty("SHOW_QUALITY",
36             Boolean.TRUE.toString());
37     Cache.applicationProperties.setProperty("SHOW_CONSERVATION",
38             Boolean.TRUE.toString());
39     Cache.applicationProperties.setProperty("SHOW_OCCUPANCY",
40             Boolean.TRUE.toString());
41     Cache.applicationProperties.setProperty("SHOW_IDENTITY",
42             Boolean.TRUE.toString());
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 briefly for it to run;
88      * NB there is no guarantee when, or whether, it will do so
89      */
90     System.gc();
91     waitFor(100);
92
93     /*
94      * a second gc() call should not be necessary - but it is!
95      * the test passes with it, and fails without it
96      */
97     System.gc();
98     waitFor(100);
99
100     /*
101      * check used memory is 'reasonably low'
102      */
103     long availableMemory = Runtime.getRuntime().totalMemory() / ONE_MB;
104     long freeMemory = Runtime.getRuntime().freeMemory() / ONE_MB;
105     long usedMemory = availableMemory - freeMemory;
106
107     /*
108      * sanity check - fails if any frame was added after
109      * closeAll_actionPerformed
110      */
111     assertEquals(Desktop.instance.getAllFrames().length, 0);
112
113     /*
114      * if this assertion fails
115      * - set a breakpoint here
116      * - run jvisualvm to inspect a heap dump of Jalview
117      * - identify large objects in the heap and their referers
118      * - fix code as necessary to null the references on close
119      */
120     System.out.println("Used memory after gc = " + usedMemory + "MB");
121     assertTrue(usedMemory < expectedMax, String.format(
122             "Used memory %d should be less than %d (Recommend running test manually to verify)",
123             usedMemory,
124             expectedMax));
125   }
126
127   /**
128    * Loads an alignment from file and exercises various operations in Jalview
129    * 
130    * @param f
131    */
132   protected void doStuffInJalview(File f)
133   {
134     /*
135      * load alignment, wait for consensus and other threads to complete
136      */
137     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(f.getPath(),
138             DataSourceType.FILE);
139     while (af.getViewport().isCalcInProgress())
140     {
141       waitFor(200);
142     }
143
144     /*
145      * set a selection group - potential memory leak if it retains
146      * a reference to the alignment
147      */
148     SequenceGroup sg = new SequenceGroup();
149     sg.setStartRes(0);
150     sg.setEndRes(100);
151     AlignmentI al = af.viewport.getAlignment();
152     for (int i = 0; i < al.getHeight(); i++)
153     {
154       sg.addSequence(al.getSequenceAt(i), false);
155     }
156     af.viewport.setSelectionGroup(sg);
157
158     /*
159      * compute Tree and PCA (on all sequences, 100 columns)
160      */
161     af.openTreePcaDialog();
162     CalculationChooser dialog = af.alignPanel.getCalculationDialog();
163     dialog.openPcaPanel("BLOSUM62", dialog.getSimilarityParameters(true));
164     dialog.openTreePanel("BLOSUM62", dialog.getSimilarityParameters(false));
165
166     /*
167      * wait until Tree and PCA have been computed
168      */
169     while (af.viewport.getCurrentTree() == null
170             && dialog.getPcaPanel().isWorking())
171     {
172       waitFor(10);
173     }
174
175     /*
176      * give Swing time to add the PCA panel (?!?)
177      */
178     waitFor(100);
179   }
180
181   /**
182    * Wait for waitMs miliseconds
183    * 
184    * @param waitMs
185    */
186   protected void waitFor(int waitMs)
187   {
188     try
189     {
190       Thread.sleep(waitMs);
191     } catch (InterruptedException e)
192     {
193     }
194   }
195
196   /**
197    * Generates an alignment and saves it in a temporary file, to be loaded by
198    * Jalview. We use a peptide alignment (so Conservation and Quality are
199    * calculated), which is wide enough to ensure Consensus, Conservation and
200    * Occupancy have a significant memory footprint (if not removed from the
201    * heap).
202    * 
203    * @return
204    * @throws IOException
205    */
206   private File generateAlignment() throws IOException
207   {
208     File f = File.createTempFile("MemoryTest", "fa");
209     PrintStream ps = new PrintStream(f);
210     AlignmentGenerator ag = new AlignmentGenerator(false, ps);
211     int width = 100000;
212     int height = 100;
213     ag.generate(width, height, 0, 10, 15);
214     return f;
215   }
216 }