ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/ContextSwitchTest.java
Revision: 1.3
Committed: Thu Sep 15 16:55:40 2005 UTC (18 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.2: +14 -11 lines
Log Message:
Misc minor test improvements

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7 dl 1.1 import java.util.concurrent.*;
8     import java.util.concurrent.locks.*;
9     import java.util.concurrent.atomic.*;
10     import java.util.*;
11    
12     public final class ContextSwitchTest {
13     final static int iters = 1000000;
14     static AtomicReference turn = new AtomicReference();
15     public static void main(String[] args) throws Exception {
16 dl 1.3 test();
17     test();
18     test();
19     }
20    
21     static void test() throws Exception {
22 dl 1.1 MyThread a = new MyThread();
23     MyThread b = new MyThread();
24     a.other = b;
25     b.other = a;
26     turn.set(a);
27     long startTime = System.nanoTime();
28     a.start();
29     b.start();
30     a.join();
31     b.join();
32     long endTime = System.nanoTime();
33     int np = a.nparks + b.nparks;
34 dl 1.3 System.out.println("Average time: " +
35     ((endTime - startTime) / np) +
36     "ns");
37 dl 1.1 }
38    
39     static final class MyThread extends Thread {
40     volatile Thread other;
41     volatile int nparks;
42    
43     public void run() {
44 dl 1.3 final AtomicReference t = turn;
45     final Thread other = this.other;
46     if (turn == null || other == null)
47     throw new NullPointerException();
48 dl 1.1 int p = 0;
49     for (int i = 0; i < iters; ++i) {
50 dl 1.3 while (!t.compareAndSet(other, this)) {
51 dl 1.1 LockSupport.park();
52     ++p;
53     }
54     LockSupport.unpark(other);
55     }
56     LockSupport.unpark(other);
57     nparks = p;
58     System.out.println("parks: " + p);
59    
60     }
61     }
62     }
63    
64