1 /* 2 * Copyright (C) 2010 The Guava Authors 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 com.google.common.util.concurrent; 18 19 import com.google.caliper.BeforeExperiment; 20 import com.google.caliper.Benchmark; 21 import com.google.caliper.Param; 22 import java.lang.reflect.Constructor; 23 import java.util.concurrent.BlockingQueue; 24 25 /** 26 * Benchmarks for {@link Monitor}. 27 * 28 * @author Justin T. Sampson 29 */ 30 public class MonitorBenchmark { 31 32 @Param({"10", "100", "1000"}) 33 int capacity; 34 35 @Param({"Array", "Priority"}) 36 String queueType; 37 38 @Param boolean useMonitor; 39 40 private BlockingQueue<String> queue; 41 private String[] strings; 42 43 @BeforeExperiment 44 @SuppressWarnings("unchecked") setUp()45 void setUp() throws Exception { 46 String prefix = 47 (useMonitor ? "com.google.common.util.concurrent.MonitorBased" : "java.util.concurrent."); 48 String className = prefix + queueType + "BlockingQueue"; 49 Constructor<?> constructor = Class.forName(className).getConstructor(int.class); 50 queue = (BlockingQueue<String>) constructor.newInstance(capacity); 51 52 strings = new String[capacity]; 53 for (int i = 0; i < capacity; i++) { 54 strings[i] = String.valueOf(Math.random()); 55 } 56 } 57 58 @Benchmark addsAndRemoves(int reps)59 void addsAndRemoves(int reps) { 60 int capacity = this.capacity; 61 BlockingQueue<String> queue = this.queue; 62 String[] strings = this.strings; 63 for (int i = 0; i < reps; i++) { 64 for (int j = 0; j < capacity; j++) { 65 queue.add(strings[j]); 66 } 67 for (int j = 0; j < capacity; j++) { 68 queue.remove(); 69 } 70 } 71 } 72 } 73