繁体   English   中英

java.util.LinkedList中的NPE addBefore方法

[英]NPE in java.util.LinkedList addBefore method

不知何故,我在这里用JDK 1.6.0_14得到一个空指针异常:

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);
}

我的猜测是跨多个线程不正确地共享List。 我猜这个列表正由两个不同的线程同时修改。

最有可能的是, (LinkedList<MyObject>) session.getAttribute(MY_LIST_KEY)返回null
更新:正如注释中正确指出的那样, getAttribute()不能返回null ,否则stacktrace不会指向LinkedList内部。 所以,我的建议是错误的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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