Benjamin Fell
Benjamin Fell

Reputation: 413

When would SharedPreferences apply() and commit() fail?

I'm using SharedPreferences to persist user's data in my application. I know the difference between commit() and apply() methods, but I've noticed that commit() returns true if the new values were successfully written to persistent storage and apply() does not.

What are the reasons that could cause a commit() method to return false or a apply() method to fail?

Upvotes: 8

Views: 1117

Answers (1)

Snild Dolkow
Snild Dolkow

Reputation: 6866

Let's take a look at the source code for commit():

    public boolean commit() {
        MemoryCommitResult mcr = commitToMemory();
        SharedPreferencesImpl.this.enqueueDiskWrite(
            mcr, null /* sync write on this thread okay */);
        try {
            mcr.writtenToDiskLatch.await();
        } catch (InterruptedException e) {
            return false;
        }
        notifyListeners(mcr);
        return mcr.writeToDiskResult;
    }

In other words, commit() will return false if the thread is interrupted while waiting for the disk write to finish, or if the disk write fails for some reason (most likely because the disk was full).

Upvotes: 6

Related Questions