java - Problems implementing BlockingQueue from scratch -


i'm trying build own variant of blockingqueue based off 1 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 reason when try run threads 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 exception

exception in thread "thread-3" java.lang.nullpointerexception @ threadsafecontainer.remove(threadsafecontainer.java:52) @ threadpractice$2.run(threadpractice.java:17) @ java.lang.thread.run(unknown source)

i can remove error changing size == 0 front == null still doesnt output same.

currently, if call remove() ever removes last element, end front == null end == //the last created node. means next call add update end, not front, , corresponding call remove() throw npe.

you can either check front == null @ end of remove(), or change test in add end == null size == 0 or front == null.

as aside, if you're posting stack trace, it's helpful add comment indicating line in snippet corresponds line numbers in exception.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -