当 LinkedList 大小为 -1 时

When LinkedList size is -1

我在 java 1.7 项目中遇到这个异常:

Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: -1
   at java.util.LinkedList.checkPositionIndex(LinkedList.java:558) ~[na:1.7.0_251]
   at java.util.LinkedList.listIterator(LinkedList.java:865) ~[na:1.7.0_251]
   at java.util.AbstractList.listIterator(AbstractList.java:299) ~[na:1.7.0_251]
   at java.util.AbstractSequentialList.iterator(AbstractSequentialList.java:239) ~[na:1.7.0_251]
   at com.project.exceptions.handlers.JsfExceptionHandler.handle(JsfExceptionHandler.java:74) ~[project-0.0.1-SNAPSHOT.jar:na]
   at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119) ~[jsf-impl-2.1.13-redhat-1.jar!/:2.1.13-redhat-1]
   at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) ~[jsf-impl-2.1.13-redhat-1.jar!/:2.1.13-redhat-1]
   at org.springframework.faces.webflow.FlowLifecycle.render(FlowLifecycle.java:80) ~[spring-faces-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   at org.springframework.faces.webflow.JsfView.render(JsfView.java:89) ~[spring-faces-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   at org.springframework.webflow.engine.ViewState.render(ViewState.java:296) ~[spring-webflow-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   at org.springframework.webflow.engine.ViewState.resume(ViewState.java:207) ~[spring-webflow-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   at org.springframework.webflow.engine.Flow.resume(Flow.java:545) [spring-webflow-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:258) [spring-webflow-2.3.2.RELEASE.jar:2.3.2.RELEASE]
   ... 62 common frames omitted

但是我不知道在什么情况下 LinkedList 的大小可以是 -1,难道不是正数吗?有什么建议吗?

自定义异常处理程序代码(第 74 行是 for)

    public class JsfExceptionHandler extends ExceptionHandlerWrapper {
        ...
        @Override
        public void handle() throws FacesException {
            FacesContext fc = ContextUtils.getFacesContextInstance();
            for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
               ...
            }
        }
    }

想到的唯一解释是,如果链表正在通过线路传递,并且发送方在有效负载中明确将其大小设置为 -1。

然后端点会尝试并可能成功地通过反射将大小设置为 -1。

但这是无稽之谈。

如果我 运行 这段代码几次,我能够重现 LinkedList 的大小为 -1:

         try {
            LinkedList<Integer> integers = new LinkedList<>();
            integers.add(1);
            new Thread(() -> {
                try {
                    Thread.sleep(1950);
                    integers.removeFirst();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

            Thread.sleep(1950);
            integers.removeFirst();


            System.out.println(integers.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

由于 LinkedList 不是线程安全的,尝试从不同线程同时从 LinkedList 实例中删除一些元素可能会导致大小为 -1。