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; + } + } +}