From ea7338aa75cc2004944cd9797784f2eb791e6518 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Mon, 28 Oct 2024 01:07:05 +0530 Subject: [PATCH] Add OOP/Java/Assignments/FISAC/Q6.java --- OOP/Java/Assignments/FISAC/Q6.java | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 OOP/Java/Assignments/FISAC/Q6.java diff --git a/OOP/Java/Assignments/FISAC/Q6.java b/OOP/Java/Assignments/FISAC/Q6.java new file mode 100644 index 0000000..f5954b7 --- /dev/null +++ b/OOP/Java/Assignments/FISAC/Q6.java @@ -0,0 +1,34 @@ +class QueueFullException extends RuntimeException {} +class QueueEmptyException extends RuntimeException {} + +class ThreadSafeQueue { + private final Object lock = new Object(); + private final T[] queue; + private int size = 0; + private int front = 0; + private int rear = 0; + + @SuppressWarnings("unchecked") + public ThreadSafeQueue() { + queue = (T[]) new Object[10]; + } + + public void enqueue(T item) { + synchronized (lock) { + if (size >= 10) throw new QueueFullException(); + queue[rear] = item; + rear = (rear + 1) % queue.length; + size++; + } + } + + public T dequeue() { + synchronized (lock) { + if (size == 0) throw new QueueEmptyException(); + T item = queue[front]; + front = (front + 1) % queue.length; + size--; + return item; + } + } +}