I'm trying to implement my own blocking queue using wait-notify for producer-consumer pattern. The producer will produce a random string, and the consumer will consume the string and count it if the number of vowels is greater than 30%.
Queue:
public class Queue {
private LinkedList<String> queue;
private int size;
private Object notEmpty = new Object();
private Object notFull = new Object();
public Queue(int size) {
this.queue = new LinkedList<>();
this.size = size;
}
public synchronized void insert(String str) throws InterruptedException {
while (queue.size() == size) {
notFull.wait();
}
queue.add(str);
notEmpty.notifyAll();
}
public synchronized String remove() throws InterruptedException {
while (queue.isEmpty()) {
notEmpty.wait();
}
String str = queue.remove();
notFull.notifyAll();
return str;
}
}
Producer:
public class Producer implements Runnable{
private Queue queue;
public Producer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
queue.insert(StringUtils.generateRandomString((100000)));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Consumer:
public class Consumer implements Runnable {
private Queue queue;
public static int count;
public Consumer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
String str = queue.remove();
if ((double) StringUtils.countVowels(str) / str.length() >= 0.3) {
count++;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Error:
java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.mambu.assignment3.Queue.insert
at com.mambu.assignment3.Producer.run
Q: I don't understand why am I getting this error.