1 /* 2 * Copyright 2019 Google LLC 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 io.perfmark.java7; 18 19 import io.perfmark.impl.Generator; 20 import java.lang.invoke.MethodHandle; 21 import java.lang.invoke.MethodHandles; 22 import java.lang.invoke.MutableCallSite; 23 24 final class SecretMethodHandleGenerator { 25 26 // UsedReflectively 27 public static final class MethodHandleGenerator extends Generator { 28 private static final MutableCallSite currentGeneration = 29 new MutableCallSite(MethodHandles.constant(long.class, 0)); 30 private static final MutableCallSite[] currentGenerations = 31 new MutableCallSite[] {currentGeneration}; 32 private static final MethodHandle currentGenerationGetter = currentGeneration.dynamicInvoker(); 33 MethodHandleGenerator()34 public MethodHandleGenerator() {} 35 36 @Override getGeneration()37 public long getGeneration() { 38 try { 39 return (long) currentGenerationGetter.invoke(); 40 } catch (Throwable throwable) { 41 return FAILURE; 42 } 43 } 44 45 @Override setGeneration(long generation)46 public void setGeneration(long generation) { 47 currentGeneration.setTarget(MethodHandles.constant(long.class, generation)); 48 MutableCallSite.syncAll(currentGenerations); 49 } 50 51 @Override costOfGetNanos()52 public long costOfGetNanos() { 53 // Method handles compile to constants, so this is effectively free. 54 // JMH testing on a Skylake x86_64 processor shows the cost to be about 0.3ns. 55 return 0; 56 } 57 58 @Override costOfSetNanos()59 public long costOfSetNanos() { 60 // based on JMH testing on a Skylake x86_64 processor. 61 return 2_000_000; 62 } 63 } 64 SecretMethodHandleGenerator()65 private SecretMethodHandleGenerator() { 66 throw new AssertionError("nope"); 67 } 68 } 69