What is the difference between commit() and apply() in SharedPreferences?
Tier: EssentialDifficulty: Easy
commit() writes to disk synchronously and blocks until it's done, apply() updates the in-memory value immediately and writes to disk asynchronously in the background.
sharedPreferences.edit()
.putString("token", token)
.apply() // returns immediately, safe to call from the main thread
The practical differences.
- Return value.
commit()returns aBooleantelling you whether the write succeeded.apply()returns nothing, you get no confirmation the disk write finished. - Thread safety for the caller.
commit()blocks the calling thread until the write completes, which can jank the UI if called on the main thread.apply()returns immediately since the disk write happens off-thread. - Ordering guarantee.
apply()still guarantees that if youapply()and immediatelycommit()on the same file, the commit waits for any pendingapply()writes to finish first, so reads stay consistent even though the write itself is async.
The rule of thumb is to default to apply(), since almost nothing needs to block on the write finishing, and reach for commit() only in the rare case where you genuinely need the return value or need to guarantee the write landed before the very next line of code runs, like right before the process might be killed.