ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/NoopSpinLockLoops.java
Revision: 1.1
Committed: Mon May 2 19:19:38 2005 UTC (19 years ago) by dl
Branch: MAIN
Log Message:
Put misc performance tests into CVS

File Contents

# Content
1 /*
2 * @test
3 * @synopsis multiple threads using a single builtin lock
4 */
5 /*
6 * Written by Doug Lea with assistance from members of JCP JSR-166
7 * Expert Group and released to the public domain. Use, modify, and
8 * redistribute this code in any way without acknowledgement.
9 */
10
11 import java.util.concurrent.*;
12 import java.util.concurrent.locks.*;
13 import java.util.concurrent.atomic.*;
14 import java.util.*;
15
16 public final class NoopSpinLockLoops {
17 static final ExecutorService pool = Executors.newCachedThreadPool();
18 static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
19 static boolean print = false;
20 static int iters = 20000000;
21
22 public static void main(String[] args) throws Exception {
23 int maxThreads = 100;
24 if (args.length > 0)
25 maxThreads = Integer.parseInt(args[0]);
26
27 new ReentrantLockLoop(1).test();
28 new ReentrantLockLoop(1).test();
29 print = true;
30
31 int k = 1;
32 for (int i = 1; i <= maxThreads;) {
33 System.out.print("Threads: " + i);
34 new ReentrantLockLoop(i).test();
35 Thread.sleep(100);
36 if (i == k) {
37 k = i << 1;
38 i = i + (i >>> 1);
39 }
40 else
41 i = k;
42 }
43 pool.shutdown();
44 }
45
46 static final class ReentrantLockLoop implements Runnable {
47 private int v = rng.next();
48 private volatile int result = 17;
49 private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
50 private final CyclicBarrier barrier;
51 private final int nthreads;
52 private volatile int readBarrier;
53 private final AtomicInteger spinlock = new AtomicInteger();
54 ReentrantLockLoop(int nthreads) {
55 this.nthreads = nthreads;
56 barrier = new CyclicBarrier(nthreads+1, timer);
57 }
58
59 final void test() throws Exception {
60 for (int i = 0; i < nthreads; ++i)
61 pool.execute(this);
62 barrier.await();
63 barrier.await();
64 if (print) {
65 long time = timer.getTime();
66 long tpi = time / ((long)iters * nthreads);
67 System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
68 double secs = (double)(time) / 1000000000.0;
69 System.out.println("\t " + secs + "s run time");
70 }
71
72 int r = result;
73 if (r == 0) // avoid overoptimization
74 System.out.println("useless result: " + r);
75 }
76
77 public final void run() {
78 final AtomicInteger lock = this.spinlock;
79 try {
80 barrier.await();
81 int sum = v + 1;
82 int x = sum + 1;
83 int n = iters;
84 while (n-- > 0) {
85 while (!lock.compareAndSet(0, 1)) ;
86 x = LoopHelpers.compute4(x);
87 lock.set(0);
88 if ((x += readBarrier) == 0)
89 ++readBarrier;
90
91 sum += x;
92 }
93 barrier.await();
94 result += sum;
95 }
96 catch (Exception ie) {
97 return;
98 }
99 }
100 }
101
102 }
103