This repository has been archived by the owner on Oct 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
ManagedIT.java
101 lines (77 loc) · 2.47 KB
/
ManagedIT.java
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
package eu.toolchain.concurrent;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
public class ManagedIT {
final Object REF = new Object();
// setup an direct async framework.
final Async async = CoreAsync.builder().build();
private AtomicInteger start;
private AtomicInteger stop;
private Managed<Object> managed;
@Rule
public Timeout timeout = Timeout.millis(1000);
@Before
public void setup() {
start = new AtomicInteger();
stop = new AtomicInteger();
managed = async.managed(() -> {
start.incrementAndGet();
return async.completed(REF);
}, value -> {
stop.incrementAndGet();
return async.completed();
});
}
@Test
public void testStartOnce() {
managed.start();
managed.start();
Assert.assertEquals(1, start.get());
}
@Test
public void testBorrow() throws Exception {
managed.start().join();
Assert.assertEquals(1, start.get());
final AtomicInteger finished = new AtomicInteger();
try (final Borrowed<Object> b = managed.borrow()) {
managed.stop().whenDone(finished::incrementAndGet);
Assert.assertTrue("should timeout", doesStopTimeout());
Assert.assertEquals(0, finished.get());
Assert.assertEquals(0, stop.get());
}
Assert.assertFalse("should not timeout", doesStopTimeout());
Assert.assertEquals(1, finished.get());
Assert.assertEquals(1, stop.get());
}
@Test
public void testInvalidFutureAfterStop() throws Exception {
managed.start().join();
managed.stop().join();
Assert.assertEquals(1, start.get());
Assert.assertEquals(1, stop.get());
final AtomicInteger finished = new AtomicInteger();
try (final Borrowed<Object> b = managed.borrow()) {
Assert.assertEquals(false, b.isValid());
managed.stop().whenDone(finished::incrementAndGet);
Assert.assertFalse("should not timeout", doesStopTimeout());
Assert.assertEquals(1, finished.get());
Assert.assertEquals(1, stop.get());
}
Assert.assertEquals(1, finished.get());
Assert.assertEquals(1, stop.get());
}
private boolean doesStopTimeout() throws Exception {
try {
managed.stop().join(10, TimeUnit.MILLISECONDS);
return false;
} catch (final TimeoutException e) {
return true;
}
}
}