2
2
3
3
import java .util .concurrent .ExecutorService ;
4
4
import java .util .concurrent .Executors ;
5
- import java .util .concurrent .TimeUnit ;
6
5
import java .util .concurrent .locks .StampedLock ;
7
6
8
7
/**
9
8
* @author Benjamin Winterberg
10
9
*/
11
10
public class Lock5 {
12
11
13
- private static int count = 0 ;
14
-
15
12
public static void main (String [] args ) {
16
13
ExecutorService executor = Executors .newFixedThreadPool (2 );
17
14
@@ -21,10 +18,8 @@ public static void main(String[] args) {
21
18
long stamp = lock .tryOptimisticRead ();
22
19
try {
23
20
System .out .println ("Optimistic Lock Valid: " + lock .validate (stamp ));
24
- TimeUnit . SECONDS .sleep (1 );
21
+ ConcurrentUtils .sleep (1 );
25
22
System .out .println ("Optimistic Lock Valid: " + lock .validate (stamp ));
26
- } catch (InterruptedException e ) {
27
- throw new IllegalStateException (e );
28
23
} finally {
29
24
lock .unlock (stamp );
30
25
}
@@ -34,23 +29,14 @@ public static void main(String[] args) {
34
29
long stamp = lock .writeLock ();
35
30
try {
36
31
System .out .println ("Write Lock acquired" );
37
- incrementAndSleep (2 );
32
+ ConcurrentUtils . sleep (2 );
38
33
} finally {
39
34
lock .unlock (stamp );
40
35
System .out .println ("Write done" );
41
36
}
42
37
});
43
38
44
-
45
39
ConcurrentUtils .stop (executor );
46
40
}
47
41
48
- private static void incrementAndSleep (int sleepSeconds ) {
49
- try {
50
- count ++;
51
- TimeUnit .SECONDS .sleep (sleepSeconds );
52
- } catch (InterruptedException e ) {
53
- throw new IllegalStateException (e );
54
- }
55
- }
56
42
}
0 commit comments