代码之家  ›  专栏  ›  技术社区  ›  Stefan Kendall

java.util.LinkedList addBefore方法中的NPE

  •  3
  • Stefan Kendall  · 技术社区  · 14 年前

    不知怎么的,我在JDK 1.6.0u14中得到了一个空指针异常:

    HttpSession session = request.getSession(true);
    LinkedList<MyObject> list = (LinkedList<MyObject>) session.getAttribute(MY_LIST_KEY);
    ....
    list.addFirst( new MyObject(str1, str2, map) );
    

    然后,我明白了:

     at java.util.LinkedList.addBefore(LinkedList.java:779)
    

    方法如下:

    private Entry<E> addBefore(E e, Entry<E> entry) {
        Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
        newEntry.previous.next = newEntry;//this line NPEs
        newEntry.next.previous = newEntry;
        size++;
        modCount++;
        return newEntry;
    }
    

    public void addFirst(E e) {
        addBefore(e, header.next);
    }
    

    是否有任何奇怪的方法可以序列化/反序列化列表,以破坏头条目,从而导致这种情况发生?我不明白这怎么可能会失败。

    LinkedList

    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();
    
        // Write out size
        s.writeInt(size);
    
        // Write out all elements in the proper order.
        for (Entry e = header.next; e != header; e = e.next)
            s.writeObject(e.element);
    }
    
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();
    
        // Read in size
        int size = s.readInt();
    
        // Initialize header
        header = new Entry<E>(null, null, null);
        header.next = header.previous = header;
    
        // Read in all elements in the proper order.
        for (int i=0; i<size; i++)
            addBefore((E)s.readObject(), header);
    }
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   james    14 年前

    我猜在多个线程之间共享列表是不正确的。我猜这个列表同时被两个不同的线程修改了。

        2
  •  -2
  •   Victor Sorokin    14 年前

    很可能, (LinkedList<MyObject>) session.getAttribute(MY_LIST_KEY) null .
    正如评论中正确指出的, 无效的 getAttribute() 在这里,否则stacktrace不会指向 LinkedList