Skip to content

Commit db5dc24

Browse files
baljeet20maibin
authored andcommitted
BAEL-700 Guide to Java Lock API (eugenp#1239)
* BAEL-604 Introduction to apache velocity * BAEL-604 Introduction to apache velocity * BAEL-700 Guide to Java Lock APIs * BAEL-700 Guide to Java Lock APIs
1 parent d04bed8 commit db5dc24

6 files changed

Lines changed: 532 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.baeldung.concurrent.locks;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import java.util.Stack;
7+
import java.util.concurrent.ExecutorService;
8+
import java.util.concurrent.Executors;
9+
import java.util.concurrent.locks.Condition;
10+
import java.util.concurrent.locks.ReentrantLock;
11+
12+
import static java.lang.Thread.sleep;
13+
14+
public class ReentrantLockWithCondition {
15+
16+
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
17+
18+
Stack<String> stack = new Stack<>();
19+
int CAPACITY = 5;
20+
21+
ReentrantLock lock = new ReentrantLock();
22+
Condition stackEmptyCondition = lock.newCondition();
23+
Condition stackFullCondition = lock.newCondition();
24+
25+
public void pushToStack(String item) throws InterruptedException {
26+
try {
27+
lock.lock();
28+
if (stack.size() == CAPACITY) {
29+
logger.info(Thread.currentThread().getName() + " wait on stack full");
30+
stackFullCondition.await();
31+
}
32+
logger.info("Pushing the item " + item);
33+
stack.push(item);
34+
stackEmptyCondition.signalAll();
35+
} finally {
36+
lock.unlock();
37+
}
38+
39+
}
40+
41+
public String popFromStack() throws InterruptedException {
42+
try {
43+
lock.lock();
44+
if (stack.size() == 0) {
45+
logger.info(Thread.currentThread().getName() + " wait on stack empty");
46+
stackEmptyCondition.await();
47+
}
48+
return stack.pop();
49+
} finally {
50+
stackFullCondition.signalAll();
51+
lock.unlock();
52+
}
53+
}
54+
55+
public static void main(String[] args) {
56+
final int threadCount = 2;
57+
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
58+
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
59+
service.execute(() -> {
60+
for (int i = 0; i < 10; i++) {
61+
try {
62+
object.pushToStack("Item " + i);
63+
} catch (InterruptedException e) {
64+
e.printStackTrace();
65+
}
66+
}
67+
68+
});
69+
70+
service.execute(() -> {
71+
for (int i = 0; i < 10; i++) {
72+
try {
73+
logger.info("Item popped " + object.popFromStack());
74+
} catch (InterruptedException e) {
75+
e.printStackTrace();
76+
}
77+
}
78+
79+
});
80+
81+
service.shutdown();
82+
}
83+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.baeldung.concurrent.locks;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
import java.util.concurrent.TimeUnit;
9+
import java.util.concurrent.locks.ReentrantLock;
10+
11+
import static java.lang.Thread.sleep;
12+
13+
public class SharedObjectWithLock {
14+
15+
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
16+
17+
ReentrantLock lock = new ReentrantLock(true);
18+
19+
int counter = 0;
20+
21+
public void perform() {
22+
23+
lock.lock();
24+
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
25+
try {
26+
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
27+
counter++;
28+
} catch (Exception exception) {
29+
logger.error(" Interrupted Exception ", exception);
30+
} finally {
31+
lock.unlock();
32+
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
33+
}
34+
}
35+
36+
public void performTryLock() {
37+
38+
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
39+
try {
40+
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
41+
if (isLockAcquired) {
42+
try {
43+
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
44+
45+
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
46+
sleep(1000);
47+
} finally {
48+
lock.unlock();
49+
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
50+
51+
}
52+
}
53+
} catch (InterruptedException exception) {
54+
logger.error(" Interrupted Exception ", exception);
55+
}
56+
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
57+
}
58+
59+
public ReentrantLock getLock() {
60+
return lock;
61+
}
62+
63+
boolean isLocked() {
64+
return lock.isLocked();
65+
}
66+
67+
boolean hasQueuedThreads() {
68+
return lock.hasQueuedThreads();
69+
}
70+
71+
int getCounter() {
72+
return counter;
73+
}
74+
75+
public static void main(String[] args) {
76+
77+
final int threadCount = 2;
78+
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
79+
final SharedObjectWithLock object = new SharedObjectWithLock();
80+
81+
service.execute(() -> {
82+
object.perform();
83+
});
84+
service.execute(() -> {
85+
object.performTryLock();
86+
});
87+
88+
service.shutdown();
89+
90+
}
91+
92+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package com.baeldung.concurrent.locks;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
import java.util.concurrent.ExecutorService;
9+
import java.util.concurrent.Executors;
10+
import java.util.concurrent.locks.StampedLock;
11+
12+
import static java.lang.Thread.sleep;
13+
14+
public class StampedLockDemo {
15+
Map<String, String> map = new HashMap<>();
16+
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
17+
18+
private final StampedLock lock = new StampedLock();
19+
20+
public void put(String key, String value) throws InterruptedException {
21+
long stamp = lock.writeLock();
22+
23+
try {
24+
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
25+
map.put(key, value);
26+
} finally {
27+
lock.unlockWrite(stamp);
28+
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
29+
}
30+
}
31+
32+
public String get(String key) throws InterruptedException {
33+
long stamp = lock.readLock();
34+
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
35+
try {
36+
sleep(5000);
37+
return map.get(key);
38+
39+
} finally {
40+
lock.unlockRead(stamp);
41+
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
42+
43+
}
44+
45+
}
46+
47+
public String readWithOptimisticLock(String key) throws InterruptedException {
48+
long stamp = lock.tryOptimisticRead();
49+
String value = map.get(key);
50+
51+
if (!lock.validate(stamp)) {
52+
stamp = lock.readLock();
53+
try {
54+
sleep(5000);
55+
return map.get(key);
56+
57+
} finally {
58+
lock.unlock(stamp);
59+
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
60+
61+
}
62+
}
63+
return value;
64+
}
65+
66+
public static void main(String[] args) {
67+
final int threadCount = 4;
68+
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
69+
StampedLockDemo object = new StampedLockDemo();
70+
71+
Runnable writeTask = () -> {
72+
73+
try {
74+
object.put("key1", "value1");
75+
} catch (InterruptedException e) {
76+
e.printStackTrace();
77+
}
78+
};
79+
Runnable readTask = () -> {
80+
81+
try {
82+
object.get("key1");
83+
} catch (InterruptedException e) {
84+
e.printStackTrace();
85+
}
86+
};
87+
Runnable readOptimisticTask = () -> {
88+
89+
try {
90+
object.readWithOptimisticLock("key1");
91+
} catch (InterruptedException e) {
92+
e.printStackTrace();
93+
}
94+
};
95+
service.submit(writeTask);
96+
service.submit(writeTask);
97+
service.submit(readTask);
98+
service.submit(readOptimisticTask);
99+
100+
service.shutdown();
101+
102+
}
103+
104+
}

0 commit comments

Comments
 (0)