Skip to content

Commit 0c48505

Browse files
committed
feat: add BlockingQueueWorkingThreadSafe demonstrating producer-consumer pattern and thread-safe queues
Implemented BlockingQueueWorkingThreadSafe.java to showcase how BlockingQueue ensures safe communication between producer and consumer threads using put() and take(). Includes examples of ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue with concurrency characteristics and blocking behavior explained. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent a57f07a commit 0c48505

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Section 25 Collections Frameworks/Queue Interface/Blocking Queue/src/BlockingQueueWorkingThreadSafe.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,31 +50,34 @@ public class BlockingQueueWorkingThreadSafe {
5050
public static void main(String[] args) {
5151
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
5252
// BlockingQueue is interfaced so we cannot instantiate, so we wrote here implementation of ArrayBlockingQueue
53-
// A bounded, blocking Queue backed by an array.
53+
// A bounded, blocking Queue backed by a circular array.
5454

55+
// uses a single lock for both enqueue and dequeue operations
56+
// more threads --> problem
5557
Thread producer = new Thread(new Producer(queue));
5658
Thread consumer = new Thread(new Consumer(queue));
5759
producer.start();
5860
consumer.start();
5961

6062
BlockingQueue<Integer> queue1 = new LinkedBlockingQueue<>();
61-
// optionally bounded backed by LinkedList
63+
// optionally boundedly backed by LinkedList
6264
// Uses two separate locks for enqueue and dequeue operations
6365
// Higher concurrency between producers and consumers
6466

6567
BlockingQueue<String> queue2 = new PriorityBlockingQueue<>(11, Comparator.reverseOrder());
66-
67-
// unbounded
68-
// Binary Heap as array and can grow dynamically
68+
// Unbounded
69+
// Binary Heap as an array and can grow dynamically
6970
// Head is based on their natural ordering or a provided Comparator like priority queue
7071
// put won't block
7172
queue2.add("apple");
7273
queue2.add("banana");
7374
queue2.add("cherry");
7475
System.out.println(queue2);
76+
7577
BlockingQueue<Integer> queue3 = new SynchronousQueue<>();
7678
// each insert operation must wait for a corresponding remove operation by another thread and vice versa.
7779
// it cannot store elements, capacity of at most one element
80+
7881
}
7982
}
8083

@@ -93,6 +96,4 @@ public static void main(String[] args) {
9396
9497
A bounded, blocking queue backed by a circular array low memory overhead uses a single lock
9598
for both enqueue and dequeue operations
96-
97-
more threads --> problem
9899
*/

0 commit comments

Comments
 (0)