Skip to content

Commit 072b12b

Browse files
committed
feat: add ArrayBlockingQueueWorkingThreadSafe demonstrating bounded thread-safe queue with producer-consumer
Implemented ArrayBlockingQueueWorkingThreadSafe.java to illustrate how ArrayBlockingQueue manages producer-consumer synchronization using a single lock. Demonstrates blocking behavior of put() and take() methods on a fixed-capacity circular array, emphasizing bounded concurrency and thread-safe communication. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 3612c67 commit 072b12b

File tree

2 files changed

+61
-5
lines changed

2 files changed

+61
-5
lines changed

Section 25 Collections Frameworks/Queue Interface/Array Blocking Queue/src/Pending.java

Lines changed: 0 additions & 5 deletions
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import java.util.concurrent.*;
2+
3+
class Producer implements Runnable {
4+
private BlockingQueue<Integer> queue;
5+
private int value = 0;
6+
7+
public Producer(BlockingQueue<Integer> queue) {
8+
this.queue = queue;
9+
}
10+
11+
@Override
12+
public void run() {
13+
while (true) {
14+
try {
15+
System.out.println("Producer produced: " + value);
16+
queue.put(value++);
17+
Thread.sleep(1000);
18+
} catch (Exception e) {
19+
Thread.currentThread().interrupt();
20+
System.out.println("Producer interrupted");
21+
}
22+
}
23+
}
24+
}
25+
26+
class Consumer implements Runnable {
27+
private BlockingQueue<Integer> queue;
28+
29+
public Consumer(BlockingQueue<Integer> queue) {
30+
this.queue = queue;
31+
}
32+
33+
@Override
34+
public void run() {
35+
while (true) {
36+
try {
37+
Integer value = queue.take();
38+
System.out.println("Consumer consumed: " + value);
39+
Thread.sleep(2000);
40+
} catch (Exception e) {
41+
Thread.currentThread().interrupt();
42+
System.out.println("Consumer interrupted");
43+
}
44+
}
45+
}
46+
}
47+
48+
public class ArrayBlockingQueueWorkingThreadSafe {
49+
public static void main(String[] args) {
50+
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
51+
// BlockingQueue is interfaced so we cannot instantiate, so we wrote here implementation of ArrayBlockingQueue
52+
// A bounded, blocking Queue backed by a circular array.
53+
54+
// uses a single lock for both enqueue and dequeue operations
55+
// more threads --> problem
56+
Thread producer = new Thread(new Producer(queue));
57+
Thread consumer = new Thread(new Consumer(queue));
58+
producer.start();
59+
consumer.start();
60+
}
61+
}

0 commit comments

Comments
 (0)