1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import com.oracle.testlibrary.jsr292.Helper;
  25 import com.sun.management.HotSpotDiagnosticMXBean;
  26 
  27 import java.lang.management.GarbageCollectorMXBean;
  28 import java.lang.management.ManagementFactory;
  29 import java.lang.reflect.Method;
  30 import java.util.Collection;
  31 import java.util.List;
  32 import java.util.function.Function;
  33 import jdk.testlibrary.Utils;
  34 import jdk.testlibrary.TimeLimitedRunner;
  35 
  36 /**
  37  * Lambda forms caching test case class. Contains all necessary test routines to
  38  * test lambda forms caching in method handles returned by methods of
  39  * MethodHandles class.
  40  *
  41  * @author kshefov
  42  */
  43 public abstract class LambdaFormTestCase {
  44 
  45     private final static String METHOD_HANDLE_CLASS_NAME = "java.lang.invoke.MethodHandle";
  46     private final static String INTERNAL_FORM_METHOD_NAME = "internalForm";
  47     private static final double ITERATIONS_TO_CODE_CACHE_SIZE_RATIO
  48             = 45 / (128.0 * 1024 * 1024);
  49     private static final long TIMEOUT = Helper.IS_THOROUGH ? 0L : (long) (Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT) * 0.9);
  50 
  51     /**
  52      * Reflection link to {@code j.l.i.MethodHandle.internalForm} method. It is
  53      * used to get a lambda form from a method handle.
  54      */
  55     protected final static Method INTERNAL_FORM;
  56     private static final List<GarbageCollectorMXBean> gcInfo;
  57 
  58     private static long gcCount() {
  59         return gcInfo.stream().mapToLong(GarbageCollectorMXBean::getCollectionCount).sum();
  60     }
  61 
  62     static {
  63         try {
  64             Class mhClass = Class.forName(METHOD_HANDLE_CLASS_NAME);
  65             INTERNAL_FORM = mhClass.getDeclaredMethod(INTERNAL_FORM_METHOD_NAME);
  66             INTERNAL_FORM.setAccessible(true);
  67         } catch (Exception ex) {
  68             throw new Error("Unexpected exception: ", ex);
  69         }
  70 
  71         gcInfo = ManagementFactory.getGarbageCollectorMXBeans();
  72         if (gcInfo.size() == 0)  {
  73             throw new Error("No GarbageCollectorMXBeans found.");
  74         }
  75     }
  76 
  77     private final TestMethods testMethod;
  78     private static long totalIterations = 0L;
  79     private static long doneIterations = 0L;
  80     private static boolean passed = true;
  81     private static int testCounter = 0;
  82     private static int failCounter = 0;
  83     private long gcCountAtStart;
  84 
  85     /**
  86      * Test case constructor. Generates test cases with random method types for
  87      * given methods form {@code j.l.i.MethodHandles} class.
  88      *
  89      * @param testMethod A method from {@code j.l.i.MethodHandles} class which
  90      * returns a {@code j.l.i.MethodHandle}.
  91      */
  92     protected LambdaFormTestCase(TestMethods testMethod) {
  93         this.testMethod = testMethod;
  94         this.gcCountAtStart = gcCount();
  95     }
  96 
  97     public TestMethods getTestMethod() {
  98         return testMethod;
  99     }
 100 
 101     protected boolean noGCHappened() {
 102         return gcCount() == gcCountAtStart;
 103     }
 104 
 105     /**
 106      * Routine that executes a test case.
 107      */
 108     public abstract void doTest();
 109 
 110     /**
 111      * Runs a number of test cases defined by the size of testCases list.
 112      *
 113      * @param ctor constructor of LambdaFormCachingTest or its child classes
 114      * object.
 115      * @param testMethods list of test methods
 116      */
 117     public static void runTests(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
 118         long testCaseNum = testMethods.size();
 119         totalIterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
 120         System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
 121                 totalIterations, totalIterations * testCaseNum);
 122         HotSpotDiagnosticMXBean hsDiagBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
 123         long codeCacheSize = Long.parseLong(
 124                 hsDiagBean.getVMOption("ReservedCodeCacheSize").getValue());
 125         System.out.printf("Code Cache Size is %d bytes%n", codeCacheSize);
 126         long iterationsByCodeCacheSize = (long) (codeCacheSize
 127                 * ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
 128         System.out.printf("Number of iterations limited by code cache size is %d (%d cases)%n",
 129                 iterationsByCodeCacheSize, iterationsByCodeCacheSize * testCaseNum);
 130         if (totalIterations > iterationsByCodeCacheSize) {
 131             totalIterations = iterationsByCodeCacheSize;
 132         }
 133         System.out.printf("Number of iterations is set to %d (%d cases)%n",
 134                 totalIterations, totalIterations * testCaseNum);
 135         System.out.flush();
 136         TimeLimitedRunner runner = new TimeLimitedRunner(TIMEOUT, 4.0d,
 137                 () -> {
 138                     if (doneIterations >= totalIterations) {
 139                         return false;
 140                     }
 141                     System.err.println(String.format("Iteration %d:", doneIterations));
 142                     for (TestMethods testMethod : testMethods) {
 143                         LambdaFormTestCase testCase = ctor.apply(testMethod);
 144                         try {
 145                             System.err.printf("Tested LF caching feature with MethodHandles.%s method.%n",
 146                                     testCase.getTestMethod().name);
 147                             testCase.doTest();
 148                             System.err.println("PASSED");
 149                         } catch (Throwable t) {
 150                             t.printStackTrace();
 151                             System.err.println("FAILED");
 152                             passed = false;
 153                             failCounter++;
 154                         }
 155                         testCounter++;
 156                     }
 157                     doneIterations++;
 158                     return true;
 159                 });
 160         try {
 161             runner.call();
 162         } catch (Throwable t) {
 163             t.printStackTrace();
 164             System.err.println("FAILED");
 165             throw new Error("Unexpected error!");
 166         }
 167         if (!passed) {
 168             throw new Error(String.format("%d of %d test cases FAILED! %n"
 169                     + "Rerun the test with the same \"-Dseed=\" option as in the log file!",
 170                     failCounter, testCounter));
 171         } else {
 172             System.err.println(String.format("All %d test cases PASSED!", testCounter));
 173         }
 174     }
 175 }