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 package org.openjdk.bench.java.util.concurrent; 24 25 import org.openjdk.jmh.annotations.*; 26 27 import java.util.ArrayList; 28 import java.util.List; 29 import java.util.Random; 30 import java.util.concurrent.ThreadLocalRandom; 31 import java.util.concurrent.TimeUnit; 32 33 @BenchmarkMode(Mode.AverageTime) 34 @OutputTimeUnit(TimeUnit.NANOSECONDS) 35 public class ThreadLocalRandomNextInt { 36 37 @State(Scope.Benchmark) 38 public static class Global { 39 public ThreadLocal<Random> tlr; 40 private List<ThreadLocal<Integer>> contaminators; // reachable, non-garbage-collectable 41 42 @Setup(Level.Trial) 43 public void setup() { 44 tlr = new ThreadLocal<Random>() { 45 @Override 46 protected Random initialValue() { 47 return java.util.concurrent.ThreadLocalRandom.current(); 48 } 49 }; 50 51 // contaminate ThreadLocals 52 int contaminatorCount = Integer.getInteger("contaminators", 0); 53 contaminators = new ArrayList<>(contaminatorCount); 54 for (int i = 0; i < contaminatorCount; i++) { 55 final int finalI = i; 56 ThreadLocal<Integer> tl = new ThreadLocal<Integer>() { 57 @Override 58 protected Integer initialValue() { 59 return finalI; 60 } 61 }; 62 contaminators.add(tl); 63 tl.get(); 64 } 65 } 66 } 67 68 @State(Scope.Thread) 69 public static class Local { 70 public java.util.concurrent.ThreadLocalRandom tlr; 71 72 @Setup(Level.Trial) 73 public void setup() { 74 tlr = java.util.concurrent.ThreadLocalRandom.current(); 75 } 76 } 77 78 @Benchmark 79 public int baseline(Local l) { 80 return l.tlr.nextInt(); 81 } 82 83 @Benchmark 84 public int testJUC() { 85 return java.util.concurrent.ThreadLocalRandom.current().nextInt(); 86 } 87 88 @Benchmark 89 public int testLang(Global g) { 90 return g.tlr.get().nextInt(); 91 } 92 93 }