blob: 88c7a962c953b1bf811807109f7898f09eabfc44 (
plain) (
blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import java.util.Iterator;
import org.junit.Test;
/**
* Check we keep the consistent view when reading and writing in parallell.
*
* @author <a href="mailto:steinar@yahoo-inc.com">Steinar Knutsen</a>
*/
public class ThreadRobustListTestCase {
private static class Writer implements Runnable {
private final ThreadRobustList<String> l;
private final Receiver<Boolean> sharedLock;
public Writer(final ThreadRobustList<String> l,
final Receiver<Boolean> sharedLock) {
this.sharedLock = sharedLock;
this.l = l;
}
@Override
public void run() {
for (int i = 0; i < 5; ++i) {
l.add(String.valueOf(i));
}
sharedLock.put(Boolean.TRUE);
for (int i = 5; i < 100 * 1000; ++i) {
l.add(String.valueOf(i));
}
}
}
private static class Reader implements Runnable {
private final ThreadRobustList<String> l;
private final Receiver<Boolean> sharedLock;
public Reader(final ThreadRobustList<String> l,
final Receiver<Boolean> sharedLock) {
this.sharedLock = sharedLock;
this.l = l;
}
@Override
public void run() {
int n;
int previous;
try {
sharedLock.get(5 * 60 * 1000);
} catch (final InterruptedException e) {
fail("Test interrupted.");
}
n = countElements();
assertFalse(n < 5);
previous = n;
for (int i = 0; i < 1000; ++i) {
int reverse = reverseCountElements();
n = countElements();
assertFalse(n < reverse);
assertFalse(n < previous);
previous = n;
}
}
private int reverseCountElements() {
int n = 0;
for (final Iterator<String> j = l.reverseIterator(); j.hasNext(); j.next()) {
++n;
}
return n;
}
private int countElements() {
int n = 0;
for (final Iterator<String> j = l.iterator(); j.hasNext(); j.next()) {
++n;
}
return n;
}
}
@Test
public final void test() throws InterruptedException {
final ThreadRobustList<String> container = new ThreadRobustList<>();
final Receiver<Boolean> lock = new Receiver<>();
final Reader r = new Reader(container, lock);
final Writer w = new Writer(container, lock);
final Thread wt = new Thread(w);
wt.start();
r.run();
wt.join();
}
}
|