Tuy Sotheara
Tuy Sotheara

Reputation: 13

Java - Infinity Loop Singleton class method call

I've a question about singleton class. When I call method next(), I expect that mProcessIndex will be increased but in reality, it won't so it causes stackoverflow error. So, the question is what is correct way to modify mProcessIndex value?

Code below:

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

Upvotes: 0

Views: 221

Answers (2)

puneet_0303
puneet_0303

Reputation: 207

Your next() function goes into infinite recursive loop as the same is called before incrementing the mProcessIndex.Therefore mProcessIndex is never incremented.Call mProcessIndex++ before next();

Upvotes: 0

Viet
Viet

Reputation: 3409

The problem is in :

next();
mProcessIndex++;

Should be:

mProcessIndex++;
next();

Upvotes: 1

Related Questions