View Javadoc

1   /***
2    *  Copyright 2003-2010 Terracotta, Inc.
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package net.sf.ehcache;
18  
19  
20  import org.junit.After;
21  import org.junit.Assert;
22  import static org.junit.Assert.assertTrue;
23  import org.junit.Before;
24  
25  import javax.management.MBeanServer;
26  import javax.management.MBeanServerFactory;
27  import java.io.File;
28  import java.io.IOException;
29  import java.lang.reflect.Method;
30  import java.util.ArrayList;
31  import java.util.List;
32  
33  import org.junit.Ignore;
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  
37  
38  /***
39   * Common fields and methods required by most test cases
40   *
41   * @author <a href="mailto:gluck@thoughtworks.com">Greg Luck</a>
42   * @version $Id: AbstractCacheTest.java 2154 2010-04-06 02:45:52Z cdennis $
43   */
44  @Ignore
45  public abstract class AbstractCacheTest {
46  
47      /***
48       * Where the config is
49       */
50      public static final String SRC_CONFIG_DIR = "src/main/config/";
51  
52      /***
53       * Where the test config is
54       */
55      public static final String TEST_CONFIG_DIR = "src/test/resources/";
56      /***
57       * Where the test classes are compiled.
58       */
59      public static final String TEST_CLASSES_DIR = "target/test-classes/";
60  
61  
62      private static final Logger LOG = LoggerFactory.getLogger(AbstractCacheTest.class.getName());
63  
64      /***
65       * name for sample cache 1
66       */
67      protected final String sampleCache1 = "sampleCache1";
68      /***
69       * name for sample cache 2
70       */
71      protected final String sampleCache2 = "sampleCache2";
72      /***
73       * the CacheManager instance
74       */
75      protected CacheManager manager;
76  
77      /***
78       * setup test
79       */
80      @Before
81      public void setUp() throws Exception {
82          manager = CacheManager.create();
83      }
84  
85      /***
86       * teardown
87       */
88      @After
89      public void tearDown() throws Exception {
90          if (manager != null) {
91              manager.shutdown();
92          }
93      }
94  
95  
96      /***
97       * Force the VM to grow to its full size. This stops SoftReferences from being reclaimed in favour of
98       * Heap growth. Only an issue when a VM is cold.
99       */
100     static public void forceVMGrowth() {
101         allocateFiftyMegabytes();
102         System.gc();
103         try {
104             Thread.sleep(200);
105         } catch (InterruptedException e) {
106             //
107         }
108         System.gc();
109     }
110 
111     private static void allocateFiftyMegabytes() {
112         byte[] forceVMGrowth = new byte[50000000];
113     }
114 
115     /***
116      * @param name
117      * @throws IOException
118      */
119     protected void deleteFile(String name) throws IOException {
120         String diskPath = System.getProperty("java.io.tmpdir");
121         final File diskDir = new File(diskPath);
122         File dataFile = new File(diskDir, name + ".data");
123         if (dataFile.exists()) {
124             dataFile.delete();
125         }
126         File indexFile = new File(diskDir, name + ".index");
127         if (indexFile.exists()) {
128             indexFile.delete();
129         }
130     }
131 
132     /***
133      * Measure memory used by the VM.
134      *
135      * @return
136      * @throws InterruptedException
137      */
138     protected long measureMemoryUse() throws InterruptedException {
139         System.gc();
140         Thread.sleep(2000);
141         System.gc();
142         return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
143     }
144 
145 
146 
147     /***
148      * Runs a set of threads, for a fixed amount of time.
149      *
150      * Throws an exception if there are throwables during the run.
151      */
152     protected void runThreads(final List executables) throws Exception {
153         int failures = runThreadsNoCheck(executables);
154             LOG.info(failures + " failures");
155             //CHM does have the occasional very slow time.
156             assertTrue("Failures = " + failures, failures <= 35);
157     }
158 
159 
160     /***
161      * Runs a set of threads, for a fixed amount of time.
162      *
163      * Does not fail if throwables are thrown.
164      * @return the number of Throwables thrown while running
165      */
166     protected int runThreadsNoCheck(final List executables) throws Exception {
167       return runThreadsNoCheck(executables, false);
168     }
169 
170   /***
171    * Runs a set of threads, for a fixed amount of time.
172    *
173    * Does not fail if throwables are thrown.
174    * @param executables the list of executables to execute
175    * @param explicitLog whether to log detailed AsserttionErrors or not
176    * @return the number of Throwables thrown while running
177    */
178     protected int runThreadsNoCheck(final List executables, final boolean explicitLog) throws Exception {
179 
180         final long endTime = System.currentTimeMillis() + 10000;
181         final List<Throwable> errors = new ArrayList<Throwable>();
182 
183         // Spin up the threads
184         final Thread[] threads = new Thread[executables.size()];
185         for (int i = 0; i < threads.length; i++) {
186             final Executable executable = (Executable) executables.get(i);
187             threads[i] = new Thread() {
188                 @Override
189                 public void run() {
190                     try {
191                         // Run the thread until the given end time
192                         while (System.currentTimeMillis() < endTime) {
193                             Assert.assertNotNull(executable);
194                             executable.execute();
195                         }
196                     } catch (Throwable t) {
197                         // Hang on to any errors
198                         errors.add(t);
199                         if (!explicitLog && t instanceof AssertionError) {
200                             LOG.info("Throwable " + t + " " + t.getMessage());
201                         } else {
202                             LOG.error("Throwable " + t + " " + t.getMessage(), t);
203                         }
204                     }
205                 }
206             };
207             threads[i].start();
208         }
209 
210         // Wait for the threads to finish
211         for (Thread thread : threads) {
212             thread.join();
213         }
214 
215 //        if (errors.size() > 0) {
216 //            for (Throwable error : errors) {
217 //                LOG.info("Error", error);
218 //            }
219 //        }
220         return errors.size();
221     }
222 
223     /***
224      * Obtains an MBeanServer, which varies with Java version
225      *
226      * @return
227      */
228     public MBeanServer createMBeanServer() {
229         try {
230             Class managementFactoryClass = Class.forName("java.lang.management.ManagementFactory");
231             Method method = managementFactoryClass.getMethod("getPlatformMBeanServer", (Class[]) null);
232             return (MBeanServer) method.invoke(null, (Object[]) null);
233         } catch (Exception e) {
234             LOG.info("JDK1.5 ManagementFactory not found. Falling back to JMX1.2.1", e);
235             return MBeanServerFactory.createMBeanServer("SimpleAgent");
236         }
237     }
238 
239 
240     /***
241      * A runnable, that can throw an exception.
242      */
243     protected interface Executable {
244         /***
245          * Executes this object.
246          *
247          * @throws Exception
248          */
249         void execute() throws Exception;
250     }
251 
252 }