SharedPreferences
commit
apply
Android
data storage

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, and String.

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:

  1. 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 using commit() 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.
  2. Return Value
    • commit(): Returns a boolean indicating 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.
  3. Data Consistency Guarantees
    • commit(): Ensures data consistency by guaranteeing that all changes are written successfully to disk before it can return true.
    • 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

Featurecommit()apply()
ExecutionSynchronousAsynchronous
Thread BlockingBlocks calling threadNon-blocking
Return Valueboolean (success/failure)None
Data Consistency GuaranteeImmediate consistency (pending success)Eventual consistency
Use Case RecommendationBackground threads or critical writesMain 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.

java
1SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
2SharedPreferences.Editor editor = sharedPreferences.edit();
3editor.putBoolean("notifications_enabled", true);
4boolean success = editor.commit();  // Guarantees data should be written before returning
5
6if (success) {
7    Log.d("SharedPreferences", "Settings saved successfully.");
8} else {
9    Log.e("SharedPreferences", "Failed to save settings.");
10}

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.

java
1SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
2SharedPreferences.Editor editor = sharedPreferences.edit();
3editor.putBoolean("draft_mode_enabled", true);
4editor.apply();  // Does not block, faster on the main thread, changes saved in the background
5
6Log.d("SharedPreferences", "Draft mode preference saved.");

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.


Course illustration
Course illustration

All Rights Reserved.