001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.monitoring.counters;
018
019 import org.apache.commons.monitoring.Role;
020 import org.apache.commons.monitoring.store.DefaultDataStore;
021 import org.junit.Test;
022
023 import java.util.concurrent.ExecutorService;
024 import java.util.concurrent.Executors;
025 import java.util.concurrent.TimeUnit;
026
027 import static org.junit.Assert.assertEquals;
028
029 public class CounterBench implements Runnable {
030 private static final int THREADS = 30;
031 private static final int LOOPS = 20000000;
032
033 private Counter counter;
034 private String mode;
035
036 @Test
037 public void defaultCounter() throws Exception {
038 mode = "RentrantLockCounter";
039 counter = new DefaultCounter(new Counter.Key(Role.FAILURES, mode), new DefaultDataStore());
040 runConcurrent();
041 }
042
043 private void runConcurrent() throws InterruptedException {
044 final long start = System.nanoTime();
045 final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
046 for (int i = 0; i < LOOPS; i++) {
047 pool.submit(this);
048 }
049 pool.shutdown();
050 pool.awaitTermination(60, TimeUnit.SECONDS);
051
052 final long duration = System.nanoTime() - start;
053 System.out.printf("%s : %,d ns/operation %n\n", mode, duration / LOOPS);
054 assertEquals(LOOPS, counter.getSum(), 0);
055
056 }
057
058 public void run() {
059 counter.add(1, Unit.UNARY);
060 }
061 }
062
063