-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCustomReentrantLock.java
40 lines (35 loc) · 1.08 KB
/
CustomReentrantLock.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
package by.andd3dfx.multithreading.lock;
/**
* Custom lock with reentrancy support
* <p>
* See <a href="https://jenkov.com/tutorials/java-concurrency/locks.html">article</a>
*
* @see <a href="https://youtu.be/QdvsNhf5FI4">Video solution</a>
*/
public class CustomReentrantLock implements Lock {
private boolean isLocked = false;
private Thread lockedBy;
private int lockedCount = 0;
@Override
public synchronized void lock() throws InterruptedException {
Thread callingThread = Thread.currentThread();
while (isLocked && lockedBy != callingThread) {
wait();
}
isLocked = true;
lockedCount++;
lockedBy = callingThread;
System.out.println("Locked...");
}
@Override
public synchronized void unlock() {
if (Thread.currentThread() == lockedBy) {
lockedCount--;
if (lockedCount == 0) {
isLocked = false;
System.out.println("Unlocked...");
notify();
}
}
}
}