From 00b4a8e37cfacc5d0d191f0baeb4ccb7ed58c155 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Mon, 28 Oct 2024 03:06:19 +0530 Subject: [PATCH] Update OOP/Java/Assignments/FISAC/Q10.java --- OOP/Java/Assignments/FISAC/Q10.java | 34 +++++++++-------------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/OOP/Java/Assignments/FISAC/Q10.java b/OOP/Java/Assignments/FISAC/Q10.java index 2e15fbd..524016e 100644 --- a/OOP/Java/Assignments/FISAC/Q10.java +++ b/OOP/Java/Assignments/FISAC/Q10.java @@ -1,5 +1,3 @@ -import java.util.concurrent.locks.*; - class FullException extends Exception { FullException(String msg) { super(msg); } } @@ -7,31 +5,19 @@ class FullException extends Exception { class Box { private T[] items = (T[]) new Object[3]; private int count = 0; - private Lock lock = new ReentrantLock(); - private Condition notFull = lock.newCondition(), notEmpty = lock.newCondition(); - void add(T item) throws FullException, InterruptedException { - lock.lock(); - try { - if (count == items.length) throw new FullException("Box is full"); - while (count == items.length) notFull.await(); - items[count++] = item; - notEmpty.signal(); - } finally { - lock.unlock(); - } + synchronized void add(T item) throws FullException, InterruptedException { + if (count == items.length) throw new FullException("Box is full"); + while (count == items.length) wait(); + items[count++] = item; + notifyAll(); } - T retrieve() throws InterruptedException { - lock.lock(); - try { - while (count == 0) notEmpty.await(); - T item = items[--count]; - notFull.signal(); - return item; - } finally { - lock.unlock(); - } + synchronized T retrieve() throws InterruptedException { + while (count == 0) wait(); + T item = items[--count]; + notifyAll(); + return item; } boolean isEmpty() {