-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample115.java
More file actions
75 lines (63 loc) · 1.67 KB
/
Example115.java
File metadata and controls
75 lines (63 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Example 115 from page 87
//
class Example115 {
public static void main(String[] args) {
final int size = 100_000, tests = 10_000;
IntArray ia = new IntArray(size);
IntArrayVolatile iav = new IntArrayVolatile(size);
{
System.out.println("Field array not volatile:");
Timer t = new Timer();
for (int i=0; i<tests; i++)
if (!ia.isSorted())
System.out.println("Unexpected!");
System.out.printf("%10.1f us/call%n", t.check()*1E6/tests);
}
{
System.out.println("Field array volatile:");
Timer t = new Timer();
for (int i=0; i<tests; i++)
if (!iav.isSorted())
System.out.println("Unexpected!");
System.out.printf("%10.1f us/call%n", t.check()*1E6/tests);
}
}
// Simple timer, measuring wall-clock (elapsed) time in seconds
private final static class Timer {
private long start;
public Timer() {
start = System.nanoTime();
}
public double check() {
return (System.nanoTime() - start) / 1e9;
}
}
}
class IntArray {
private int[] array;
public IntArray(int length) {
array = new int[length];
for (int i=0; i<length; i++)
array[i] = 2 * i + 1;
}
public boolean isSorted() {
for (int i=1; i<array.length; i++)
if (array[i-1] > array[i])
return false;
return true;
}
}
class IntArrayVolatile {
private volatile int[] array;
public IntArrayVolatile(int length) {
array = new int[length];
for (int i=0; i<length; i++)
array[i] = 2 * i + 1;
}
public boolean isSorted() {
for (int i=1; i<array.length; i++)
if (array[i-1] > array[i])
return false;
return true;
}
}