What's the difference between commit and apply in SharedPreferences
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Android development, SharedPreferences is a commonly used API for storing user preferences or small amounts of data. It provides simple methods to save and retrieve key-value pairs of primitive data types. Among its various methods, commit() and apply() are two similar operators used to persist data changes. While they may seem interchangeable, they possess distinct differences that affect performance and behavior. This article examines those differences, discusses their implications, and provides insights on when to use each.
SharedPreferences Overview
Before delving into commit() and apply(), it's essential to understand how SharedPreferences works. Essentially, SharedPreferences offers a key-value pair storage mechanism with the following properties:
- Key: A unique string identifier for the data item.
- Value: The data associated with the key. Supported types include
int,float,long,boolean, andString.
Data changes in SharedPreferences are made through the SharedPreferences.Editor interface, which provides methods to:
- Add data (
putInt(),putBoolean(), etc.) - Remove data (
remove()) - Clear all data (
clear()) - Persist changes (
commit(),apply())
Differences Between commit() and apply()
Both commit() and apply() are used to save changes made via SharedPreferences.Editor. However, they differ in the following key aspects:
- Synchronous vs Asynchronous Execution
commit(): Saves the changes synchronously. This means it blocks the calling thread and waits for the write operation to complete before returning control. It's essential to note that usingcommit()on the main UI thread can cause performance issues and possibly lead to an Application Not Responding (ANR) error.apply(): Persists changes asynchronously without blocking the calling thread. Changes are committed in the background, making it a better choice for operations on the main thread. However, since it doesn't have to wait for the operation to complete, it's inherently faster on the calling thread.
- Return Value
commit(): Returns abooleanindicating success (true) or failure (false) of the operation. It provides a way to confirm whether the changes were committed.apply(): Does not return any value. It offers no immediate feedback regarding the success or failure of the operation.
- Data Consistency Guarantees
commit(): Ensures data consistency by guaranteeing that all changes are written successfully to disk before it can returntrue.apply(): Updates the in-memory state as soon as possible and doesn't immediately write changes to disk, which can lead to eventual consistency if multiple operations are done in rapid succession.
Summary Table
| Feature | commit() | apply() |
| Execution | Synchronous | Asynchronous |
| Thread Blocking | Blocks calling thread | Non-blocking |
| Return Value | boolean (success/failure) | None |
| Data Consistency Guarantee | Immediate consistency (pending success) | Eventual consistency |
| Use Case Recommendation | Background threads or critical writes | Main thread or less critical writes |
Example Use Cases
Using commit()
You might want to use commit() in scenarios where you need to ensure that the data is saved correctly—for instance, critical user preferences that must be available immediately after saving.
Using apply()
apply() is beneficial in non-critical operations where speed and responsiveness are prioritized, such as saving draft versions of user inputs or preferences that do not need immediate persistence.
Conclusion
Choosing between commit() and apply() in SharedPreferences ultimately depends on the specific use case and the demands of the application. If executing on the main UI thread and requiring prompt UI responsiveness, prefer apply(). In contrast, use commit() when operating from a non-UI thread or when data integrity and immediate feedback on success are critical. Understanding these differences helps ensure optimal performance and reliability in Android applications.

