Search code examples
javalinked-listnullpointerexceptiondeque

LinkedList.pollLast() throws NullPointerException


I use Java 6 Collecetions API. I need a collection that should have only N elements. I mean that if I add new element and collection already have N elements than the last element should be removed and new one add in the head of collection. I have following code fragment to do it:

class A {

  int N = 100;
  Deque dq = new LinkedList();

  void add(Object o) {
    synchronized (o) { 
      if (dq.size() == N) {
        dq.pollLast();
      }
      dq.add(o);
    }
  }

  Deque getDq() {
    return new LinkedList(dq);
  }
}

Object with type A can be accessed many users in the same time to add new element. In practice I got NullPointerException with it:

Caused by: java.lang.NullPointerException
   at java.util.LinkedList.remove(LinkedList.java:790)
   at java.util.LinkedList.removeLast(LinkedList.java:144)
   at java.util.LinkedList.pollLast(LinkedList.java:573)
   at A.add(A.java:9)

Deque.pollLast() contract doesn't say anything about NullPointerException:

Retrieves and removes the last element of this list, or returns null if this list is empty.

Also adding of elements is synchronized.

Does anyone know what is reason of exception could be?

Thanks for any ideas


Solution

  • I guess the sycronization is done on the wrong object! It should be dq but not o!

    ... synchronized (dg) { ...