Java Reference
In-Depth Information
Listing 4-11. Nonatomic Operation Example
1 public class NonAtomic {
2 static int x;
3
4 public static void main(String[] args) {
5 for (int i = 0; i < 10; i++) {
6 new Runner().start();
7 }
8 }
9
10 static class Runner extends Thread {
11 private int validCounts = 0;
12 private int invalidCounts = 0;
13
14 public void run() {
15 for (int i = 0; i < 10; i++) {
16 // synchronized (NonAtomic.class) {
17 int reference = (int) (Math.random() * 100);
18 x = reference;
19
20 // either yielding or doing something intensive
21 // should cause the problem to manifest.
22 yield();
23 // for (int y = 0; y < 20000; y++) {
24 // Math.tan(200);
25 // }
26
27 if (x == reference) {
28 validCounts++;
29 } else {
30 invalidCounts++;
31 }
32 }
33 // }
34
35 System.out.println(getName()
36 + " valid: " + validCounts
37 + " invalid: " + invalidCounts);
38 }
39 }
40 }
When you run this program, you will see that in the majority of cases, another thread has
changed the value of x between when it is set (in line 18) and when it is checked (in line 28).
An example of this is provided in Figure 4-10.
Search WWH ::




Custom Search