-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReentrantLockDemo.java
More file actions
78 lines (65 loc) · 1.98 KB
/
ReentrantLockDemo.java
File metadata and controls
78 lines (65 loc) · 1.98 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
74
75
76
77
78
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
public class ReentrantLockDemo extends ConcurrentUtils {
static int count = 0;
static ReentrantLock lock = new ReentrantLock();
static void increment() {
/*
* If another thread has already acquired the lock
* subsequent calls to lock() pause the current thread
* until the lock has been unlocked.
* Only one thread can hold the lock at any given time.
*/
/*
* if using ReentrantLock, it allows the same thread
* to acquire the same lock more than once.
* Internally, it has a counter to count the number of the lock acquisition.
* If you acquired the same lock twice, you would need to release it twice.
*
* Use case: when M1 method with lock call M2 with lock, or recursive
*/
lock.lock();
//lock.lock();
try {
count++;
} finally {
lock.unlock();
//lock.unlock();
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 10000).forEach(
i -> executor.submit(ReentrantLockDemo::increment));
executor.submit(() ->
{
lock.lock();
try {
sleep(1);
} finally {
lock.unlock();
}
});
//sleep(10);
executor.submit(() -> {
System.out.println("Locked: " + lock.isLocked());
/*
* tryLock() as an alternative to lock()
* tries to acquire the lock without pausing the current thread.
* The boolean result must be used to check
* if the lock has actually been acquired
* before accessing any shared mutable variables.
*/
boolean locked = lock.tryLock();
System.out.println("Held by me: " + lock.isHeldByCurrentThread());
System.out.println("Lock acquired: " + locked);
if(locked){
lock.unlock();
}
});
stop(executor);
System.out.println(count); // 10000
}
}