| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
import java.util.concurrent.*; |
| 18 |
import java.util.concurrent.atomic.AtomicLong; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
public class Main { |
| 24 |
public static void main(String args[]) throws Exception { |
| 25 |
b17689750TestVolatile(); |
| 26 |
b17689750TestMonitor(); |
| 27 |
} |
| 28 |
|
| 29 |
static void b17689750TestVolatile() { |
| 30 |
final B17689750TestVolatile test = new B17689750TestVolatile(); |
| 31 |
new Thread() { |
| 32 |
public void run() { |
| 33 |
test.thread1(); |
| 34 |
} |
| 35 |
}.start(); |
| 36 |
try { |
| 37 |
test.thread2(); |
| 38 |
} catch (NullPointerException expected) { |
| 39 |
System.out.println("b17689750TestVolatile passed."); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
static void b17689750TestMonitor() { |
| 44 |
final B17689750TestMonitor test = new B17689750TestMonitor(); |
| 45 |
new Thread() { |
| 46 |
public void run() { |
| 47 |
test.thread1(); |
| 48 |
} |
| 49 |
}.start(); |
| 50 |
try { |
| 51 |
test.thread2(); |
| 52 |
} catch (NullPointerException expected) { |
| 53 |
System.out.println("b17689750TestMonitor passed."); |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
class B17689750TestVolatile { |
| 59 |
private volatile int state = 0; |
| 60 |
private int[] values = { 42 }; |
| 61 |
|
| 62 |
void thread1() { |
| 63 |
while (state != 1) { } |
| 64 |
values = null; |
| 65 |
state = 2; |
| 66 |
} |
| 67 |
|
| 68 |
void thread2() { |
| 69 |
int[] vs1 = values; |
| 70 |
state = 1; |
| 71 |
while (state != 2) { } |
| 72 |
int[] vs2 = values; |
| 73 |
int v1 = vs1[0]; |
| 74 |
int v2 = vs2[0]; |
| 75 |
System.out.println("b17689750TestVolatile failed: " + v1 + ", " + v2); |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
class B17689750TestMonitor { |
| 80 |
private int state = 0; |
| 81 |
private Object lock = new Object(); |
| 82 |
private int[] values = { 42 }; |
| 83 |
|
| 84 |
void thread1() { |
| 85 |
int s; |
| 86 |
do { |
| 87 |
synchronized (lock) { |
| 88 |
s = state; |
| 89 |
} |
| 90 |
} while (s != 1); |
| 91 |
|
| 92 |
synchronized (lock) { |
| 93 |
values = null; |
| 94 |
state = 2; |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
void thread2() { |
| 99 |
int[] vs1; |
| 100 |
synchronized (lock) { |
| 101 |
vs1 = values; |
| 102 |
state = 1; |
| 103 |
} |
| 104 |
|
| 105 |
int s; |
| 106 |
do { |
| 107 |
synchronized (lock) { |
| 108 |
s = state; |
| 109 |
} |
| 110 |
} while (s != 2); |
| 111 |
|
| 112 |
int[] vs2 = values; |
| 113 |
int v1 = vs1[0]; |
| 114 |
int v2 = vs2[0]; |
| 115 |
System.out.println("b17689750TestMonitor failed: " + v1 + ", " + v2); |
| 116 |
} |
| 117 |
} |