简体   繁体   中英

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

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

... synchronized (dg) { ...

I've run your code adding using the following test

    A a = new A();
    for (int i = 0; i < 200; i++)
    {
        a.add(i);
    }
    System.out.println(a.dq);

And it all seems to work correctly. Can you provide more details on the state of the application when you get the NPE? What is the object you are trying to add? What is the state of the Dequeue at that time?

Also, you mentioned

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

Your code doesn't do that. Right now, it adds to the tail of the collection. To add it to the head, change

dq.add(o)

to

dq.addFirst(o)

see this javadoc it says

 Removes and returns the last element from this list.

first it removes object so if it is null then throws NullPointerException:

so make add(..) method synchronized and check for size before dq.pollLast();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM