1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.tests.performance.java;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.Semaphore;
16 import java.util.concurrent.atomic.AtomicInteger;
18 import org.simantics.db.testing.base.TestCommonPerf;
24 public class ThreadLocalTest extends TestCommonPerf {
26 public void test() throws Exception {
28 final ThreadLocal<AtomicInteger> local = new ThreadLocal<AtomicInteger>();
30 class CounterThread extends Thread {
32 final private Semaphore start;
33 final private AtomicInteger counter;
34 final private CountDownLatch latch;
36 public CounterThread(Semaphore start, CountDownLatch latch, AtomicInteger counter) {
38 this.counter = counter;
45 local.set(new AtomicInteger());
49 } catch (InterruptedException e) {
54 for(int i=0;i<1000000;i++) {
55 for(int j=0;j<100;j++) local.get().incrementAndGet();
60 System.out.println("work=" + work);
66 CountDownLatch latch = new CountDownLatch(8);
67 AtomicInteger counter = new AtomicInteger(0);
68 Semaphore starter = new Semaphore(0);
70 for(int i=0;i<8;i++) new CounterThread(starter, latch, counter).start();
75 long start = System.nanoTime();
77 long duration = System.nanoTime() - start;
79 System.out.println("counter=" + counter.get());
81 System.out.println("Finished in " + 1e-9*duration + "s.");
85 public void test2() throws Exception {
87 class CounterThread extends Thread {
89 final private Semaphore start;
90 final private AtomicInteger counter;
91 final private CountDownLatch latch;
93 public CounterThread(Semaphore start, CountDownLatch latch, AtomicInteger counter) {
95 this.counter = counter;
102 AtomicInteger ai = new AtomicInteger();
106 } catch (InterruptedException e) {
111 for(int i=0;i<1000000;i++) {
112 for(int j=0;j<100;j++) ai.incrementAndGet();
117 System.out.println("work=" + work);
123 CountDownLatch latch = new CountDownLatch(8);
124 AtomicInteger counter = new AtomicInteger(0);
125 Semaphore starter = new Semaphore(0);
127 for(int i=0;i<8;i++) new CounterThread(starter, latch, counter).start();
132 long start = System.nanoTime();
134 long duration = System.nanoTime() - start;
136 System.out.println("counter=" + counter.get());
138 System.out.println("Finished in " + 1e-9*duration + "s.");