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