Java - Infinity Loop Singleton类方法调用

时间:2017-04-25 03:40:22

标签: java singleton singleton-methods

我有关于单身人士课的问题。当我调用方法next()时,我希望mProcessIndex会增加但实际上它不会因此导致stackoverflow错误。那么,问题是修改mProcessIndex值的正确方法是什么?

以下代码

public class HomePopupDisplayManager {
    private static HomePopupDisplayManager sInstance;
    private List<WeakReference<HomePopupMessage>> mMessages;
    private int mProcessIndex;

    private HomePopupDisplayManager() {
        mMessages = new ArrayList<>();
        mProcessIndex = 0;
    }

    public static synchronized HomePopupDisplayManager getInstance() {
        if (sInstance == null) {
            sInstance = new HomePopupDisplayManager();
        }

        return sInstance;
    }

        public void register(@NonNull HomePopupMessage message, @IntRange(from = 0) int order) {
            mMessages.add(order, new WeakReference<>(message));
    }

    public void next() {
        if (mProcessIndex >= 0 && mProcessIndex < mMessages.size()) {
            HomePopupMessage message = mMessages.get(mProcessIndex).get();
            if (message != null) {
                next();
                mProcessIndex++;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

问题在于:

next();
mProcessIndex++;

应该是:

mProcessIndex++;
next();

答案 1 :(得分:0)

你的next()函数进入无限递归循环,因为在递增mProcessIndex之前调用它。因此mProcessIndex永远不会递增。在之前调用 mProcessIndex ++ ;