Skip to content

Commit ff448c4

Browse files
committed
locks
1 parent fc602a1 commit ff448c4

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package multithreading.locks;
2+
3+
import java.util.concurrent.TimeUnit;
4+
import java.util.concurrent.locks.Lock;
5+
import java.util.concurrent.locks.ReentrantLock;
6+
7+
/*
8+
ReentrantLock is a class which implements Lock interface
9+
10+
tryLock(): Acquires the lock only if it's free at time of invocation.
11+
Acquires the lock if it's available and returns immediately with the value true.
12+
If the lock is not available then this method will return immediately with the value false.
13+
14+
lock(): same as synchronized, will wait for the lock to be available
15+
16+
17+
If an InterruptedException or a ThreadDeath error is not handled properly, the information that the thread was interrupted will be lost.
18+
Handling this exception means either to re-throw it or manually re-interrupt the current thread by calling Thread.interrupt().
19+
Simply logging the exception is not sufficient and counts as ignoring it.
20+
B/w the moment the exception is caught and handled, is the right time to perform cleanup operations on the method's state, if needed.
21+
22+
What is the potential impact?
23+
- Failing to interrupt the thread (or to re-throw) risks delaying the thread shutdown and losing the information that the thread was interrupted
24+
probably without finishing its task.
25+
*/
26+
27+
public class BankAccount {
28+
private int balance = 100;
29+
30+
private final Lock lock = new ReentrantLock();
31+
32+
/*
33+
jab hmne esko synchronized kr diya to agar t1 access krrha to t2 access nhi kr payega
34+
chahe hm kitna bhi sleep krwa rhe ho
35+
jb tk t1 esko poora khtm nhi kr lega including this sleep, tab tk t2 nhi aayega
36+
*/
37+
// public synchronized void withdraw(int amount) {
38+
39+
public void withdraw(int amount) {
40+
System.out.println(Thread.currentThread().getName() + " attempting to withdraw " + amount);
41+
/*
42+
if(balance >= amount) {
43+
System.out.println(Thread.currentThread().getName() + " proceeding with withdrawal");
44+
try {
45+
Thread.sleep(3000);
46+
} catch (InterruptedException e) {
47+
48+
}
49+
balance -= amount;
50+
System.out.println(Thread.currentThread().getName() + " completed withdrawal. Remaining balance: " + balance);
51+
} else {
52+
System.out.println(Thread.currentThread().getName() + " insufficient balance");
53+
}
54+
*/
55+
56+
try {
57+
// Acquires the lock if it's free within the given waiting time & the current thread hasn't been interrupted
58+
if(lock.tryLock(1000, TimeUnit.MILLISECONDS)) {
59+
if(balance >= amount) {
60+
try {
61+
System.out.println(Thread.currentThread().getName() + " proceeding with withdrawal");
62+
Thread.sleep(3000); // Simulate time taken to process the withdrawal
63+
balance -= amount;
64+
System.out.println(Thread.currentThread().getName() + " completed withdrawal. Remaining balance: " + balance);
65+
} catch (Exception e) {
66+
Thread.currentThread().interrupt();
67+
} finally {
68+
lock.unlock();
69+
}
70+
} else {
71+
System.out.println(Thread.currentThread().getName() + " insufficient balance");
72+
}
73+
} else {
74+
System.out.println(Thread.currentThread().getName() + " couldn't acquire the lock, will try again later");
75+
}
76+
} catch (Exception e) {
77+
Thread.currentThread().interrupt();
78+
}
79+
if(Thread.currentThread().isInterrupted()) {
80+
System.out.println("");
81+
}
82+
}
83+
}

src/multithreading/locks/Main.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package multithreading.locks;
2+
3+
/*
4+
1. Intrinsic: These are built into every object in Java. You don't see them, but they're there.
5+
When you use a synchronized keyword, you're using these automatic locks.
6+
7+
2. Explicit: These are more advanced locks you can control yourself using the Lock class from java.util.concurrent.locks.
8+
You explicitly say when to lock & unlock, giving you more control over how & when people can write in the notebook.
9+
*/
10+
11+
public class Main {
12+
public static void main(String[] args) {
13+
BankAccount sbi = new BankAccount();
14+
Runnable task = new Runnable() {
15+
@Override
16+
public void run() {
17+
sbi.withdraw(50);
18+
}
19+
};
20+
Thread t1 = new Thread(task, "Thread 1");
21+
Thread t2 = new Thread(task, "Thread 2");
22+
t1.start();
23+
t2.start();
24+
}
25+
}

0 commit comments

Comments
 (0)