【问题标题】:IndexOutOfBoundsException in LinkedListLinkedList 中的 IndexOutOfBoundsException
【发布时间】:2020-03-24 15:22:19
【问题描述】:

我遇到了 IndexOutOfBoundsException,这对我来说似乎是不可能的。

代码:

public class SomethingCalculator {

    @Nullable
    private Config mConfig;
    @Nullable
    private Long mTime;
    final private List<Long> mLinkedList = new LinkedList<>();


    public synchronized void setupWithConfiguration(Config config, Long time) {
        //config and time are non null always
        mTime = time;
        mConfig = config;
        generatLookUp();
    }


    public synchronized void reset() {
        mConfig = null;
        mTime = null;
        mLinkedList.clear();
    }


    @Nullable
    public synchronized Long getTheValue(long ms) {
        if (mConfig == null)
            return null;

        // getting exception here
        if (ms > mLinkedList.get(mLinkedList.size() - 1)) {
            return 0l; // something
        }
        return 0l; // something
    }


    private synchronized void generatLookUp() {
        mLinkedList.clear();
        if (mConfig == null || mTime==null)
            return;
        // mLinkedList will always have size > 0 after executing this
        // based upon config this method add elements to mLinkedList

        // adding dummy values
        mLinkedList.add(1L);
        mLinkedList.add(2L);
    }
}

调用SomethingCalculator.getTheValue()时出现异常

例外:

Fatal Exception: java.lang.IndexOutOfBoundsException: Index: 4, Size: 0
 at java.util.LinkedList.checkElementIndex(LinkedList.java:565)

不确定 mMylinkedList.size() 是否返回 4,那么 mMylinkedList.get(4) 如何抛出 IndexOutOfBoundsException。

【问题讨论】:

  • 哪一行抛出异常?调试的时候是什么状态?
  • 你能提供一个minimal reproducible example吗?仅从这段代码很难判断发生了什么。是否涉及多个线程? (我知道这是同步的,但我怀疑它可能仍然相关。)
  • @Tayler ,OP 提到了哪一行..
  • 不知道为什么投反对票,请在投反对票前发表评论,这将有助于改善问题。
  • 虽然这很可能是实际代码,但它不是一个完整的示例——它指的是我们不知道的代码 (Config),并且没有任何我们可以实际运行的代码 。我们正在寻找可以复制、粘贴、编译和运行的示例,以便重现您的问题。

标签: java


【解决方案1】:

在查看生成的 AAR 后,发现 synchronized 关键字已被剥离,因此可能会发生此异常。由于 proguard 优化,synchronized 关键字已被删除。

删除了这个:

-optimizations !method/marking/synchronized

现在我可以在生成的 AAR 中看到 synchronized 关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多