I'm trying to build my own variant of BlockingQueue based off the one found here.
public class ThreadSafeContainer<E> {
private Node front;
private Node end;
private int capacity;
private int size;
public ThreadSafeContainer(int capacity) {
size = 0;
this.capacity = capacity;
}
public synchronized void add(E item) {
while (size == capacity) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (size == 0) {
notifyAll();
}
Node tmp = new Node(item);
if (end == null) {
front = tmp;
end = tmp;
} else {
end.next = tmp;
end = end.next;
}
size++;
}
public synchronized E remove() {
while (size == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (size == capacity) {
notifyAll();
}
E item = front.item;
front = front.next;
size--;
return item;
}
private class Node {
E item;
Node next;
public Node(E item) {
this.item = item;
}
}
But for some reason when I try to run threads like so
Thread thread1 = new Thread() {
public void run() {
queue.add(1);
queue.add(2);
}
};
Thread thread2 = new Thread() {
public void run() {
System.out.println(queue.remove());
System.out.println(queue.remove());
}
};
I get this exception
Exception in thread "Thread-3" java.lang.NullPointerException at ThreadSafeContainer.remove(ThreadSafeContainer.java:52) at ThreadPractice$2.run(ThreadPractice.java:17) at java.lang.Thread.run(Unknown Source)
I can remove the error by changing the size == 0 to front == null but it still doesnt output the same.