ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/ContextSwitchTest.java
Revision: 1.9
Committed: Mon Oct 12 20:16:47 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.8: +7 -0 lines
Log Message:
guard against lost unpark via JDK-8074773

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 jsr166 1.6 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
6    
7 jsr166 1.7 import java.util.*;
8 dl 1.1 import java.util.concurrent.*;
9 jsr166 1.7 import java.util.concurrent.atomic.*;
10 dl 1.1 import java.util.concurrent.locks.*;
11    
12     public final class ContextSwitchTest {
13 jsr166 1.5 static final int iters = 1000000;
14 dl 1.1 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 jsr166 1.4 System.out.println("Average time: " +
35 dl 1.3 ((endTime - startTime) / np) +
36     "ns");
37 dl 1.1 }
38    
39     static final class MyThread extends Thread {
40 jsr166 1.9
41     static {
42     // Reduce the risk of rare disastrous classloading in first call to
43     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
44     Class<?> ensureLoaded = LockSupport.class;
45     }
46    
47 dl 1.1 volatile Thread other;
48     volatile int nparks;
49    
50     public void run() {
51 dl 1.3 final AtomicReference t = turn;
52     final Thread other = this.other;
53 jsr166 1.4 if (turn == null || other == null)
54 dl 1.3 throw new NullPointerException();
55 dl 1.1 int p = 0;
56     for (int i = 0; i < iters; ++i) {
57 dl 1.3 while (!t.compareAndSet(other, this)) {
58 dl 1.1 LockSupport.park();
59     ++p;
60     }
61     LockSupport.unpark(other);
62     }
63     LockSupport.unpark(other);
64     nparks = p;
65     System.out.println("parks: " + p);
66     }
67     }
68     }