SharedPreferences vs DataStore: The Hidden Lock That Freezes Android Apps
Goodbye to Lag and ANR: A Plain-Language Deep Dive into SharedPreferences and Jetpack DataStore
In Android development, lightweight local storage is almost standard for every app: saving login tokens, dark mode switch, font size configuration and other simple key-value pairs.
For a long time, everyone has been used to using SharedPreferences (SP directly). But under the Jetpack ecosystem, Google has explicitly recommended: new projects should prefer DataStore, and SharedPreferences is no longer recommended.
Most articles introducing DataStore online just list: supports Flow, coroutines, type safety. These features are correct, but they don't get to the underlying core. From the concurrency architecture, the essential difference in one sentence:
SharedPreferences is a "lock model", DataStore is a "lock-free message model (Actor)"
Below, using plain analogies, we'll explain the underlying principles, common misunderstandings, and the hidden pitfalls of apply() all at once.
1. The fatal weakness of SharedPreferences: Lock + full disk read/write
1.1 A public bathroom with only one key (lock model)
The core implementation of SP, SharedPreferencesImpl, relies on locks to ensure multi-thread concurrency safety.
You can think of SP as a public bathroom with only one key. Whether the UI main thread, background business thread, or analytics thread reads or writes data, it must first grab this key (lock) to operate.
Thread A (background writes config) ──┐
Thread B (main thread reads switch) ──┼──▶ Compete for lock ──▶ Access SharedPreferences
Thread C (background analytics) ──┘
1.2 Why does it freeze the UI and trigger ANR?
The lock itself is not the culprit; lock + full XML rewrite is the root risk:
- SP is backed by an XML file and does not support partial modification. Even if you modify only one boolean switch, the underlying layer re-serializes all configuration and overwrites the entire XML;
- When a background thread is slowly writing to disk, if the main thread happens to read and waits for the lock, the main thread is blocked; when the main thread is blocked for too long, it directly shows a frozen UI and ANR.
1.3 Can we modify SP and optimize the lock?
Hard. The root cause is the file format limitation: XML can only be read/written as a whole, not partially updated. Multi-thread concurrent modifications easily get out of order, and the ceiling for patching on the original architecture is very low.
2. Dig deeper into the misunderstanding: commit() and apply(), apply() doesn't save you from ANR
Many people think: commit() is synchronous and blocks the main thread, so if I replace everything with async apply(), will it be safe? Answer: No, apply() just postpones the freeze, the risk still exists.
Use a delivery analogy to explain the difference:
- commit(): drive yourself to deliver, the delivery is done only when it arrives. The calling thread waits for disk write to complete, and the write time is directly counted on the current thread. When called on main thread, it freezes immediately.
- apply(): hand it to the courier, you go first. Calling apply() does two things:
- Immediately updates the in-memory cache, so subsequent reads get the new value;
- The actual XML disk write task is queued to the background queue asynchronously, and the call site does not block immediately.
The hidden pitfall of apply()
If you call apply() multiple times in a short period, background tasks of "full XML rewrite" pile up. Android, at system nodes like screen switching, onStop() going to background, will force waiting for all queued write tasks to complete. So:
- commit()'s freeze: happens at the calling line, the problem is obvious;
- apply()'s freeze/ANR: often hidden in onStop(), insidious and hard to reproduce.
| Dimension | commit() | apply() |
|---|---|---|
| Blocking timing | at the call site | at lifecycle nodes like onStop |
| ANR risk | obvious and easy to find | hidden and hard to debug |
One sentence to understand apply:
The bill is handed to an assistant, you can go first; but when you leave, the security guard stops you, you must wait until the assistant processes all backlogged bills before letting you go.
3. Jetpack DataStore's solution: four core principles
DataStore abandons the "grabbing locks" approach; the whole scheme: memory cache + Actor message queue + atomic transaction write + Flow reactive push.
3.1 Write: order slip + single clerk (Actor model)
Calling updateData / edit to modify data no longer makes multiple threads compete for a lock. It adopts the core idea of the Actor model: do not share state, only communicate through messages.
- All thread modification operations are packaged as messages and sent into a Channel message queue;
- A single coroutine processes all read/write messages in the queue serially in order;
- Only one executor exists, so no locks are needed naturally, and no concurrent conflicts occur.
Thread A ──┐
Thread B ──┼──▶ send message ──▶ Channel ──▶ single coroutine processes in order ──▶ write disk
Thread C ──┘
3.2 Writing to disk: write temporary draft first, then replace the official file (atomic transaction)
For ordinary file writes, if the app is killed mid-write or the system loses power, half-written or corrupted files can occur. DataStore uses atomic writes: first write to a temporary file, verify complete success, then replace the official data file. Either all write succeeds, or the old data is kept; no corruption.
3.3 Reading: memory cache + Flow reactive push
- First load into memory cache, subsequent reads don't go through disk IO, making reads faster;
- After data updates, proactively push to subscribers via Kotlin Flow; naturally fits Compose, MVI reactive architecture, no need for active polling to refresh.
3.4 Which of the two DataStores to choose
- Preferences DataStore: key-value mode, easy to get started, suitable for simple configs, suitable for migrating from SP;
- Proto DataStore: based on Protocol Buffers for struct definition, strong type validation, suitable for fixed structures and type-safe scenarios.
4. Full comparison table
| Dimension | SharedPreferences | DataStore |
|---|---|---|
| Concurrency model | lock contention model | Actor message queue, lock-free serial |
| IO mode | synchronous / pseudo-async (apply) | coroutine pure async |
| Atomic file write | Not supported, easily corrupted | Atomic transaction |
| ANR risk | exists, apply scenario hidden | avoided at architecture level |
| Reactive listening | Only registerListener, poor experience | Flow streaming push |
| Type safety | bare key-value, easy to make mistakes | Proto mode strong type |
5. Summary
If you only occasionally read/write small configs once, the single-call time difference is not big, and DataStore may even add a bit of coroutine scheduling and message queue overhead.
The real dividing line is concurrency stability and architecture design: SP is the old scheme of "lock + full XML rewrite", apply() just masks the immediate blocking and buries the risk in lifecycle callbacks; DataStore relies on the Actor single-coroutine message model to replace locks, combined with coroutine async, atomic write, and Flow reactive push, better suited for modern Android high-concurrency, reactive development.
Simple selection suggestion: new projects prefer DataStore; existing old projects don't have to do a one-size-fits-all full migration immediately; prioritize migration where high-frequency reads/writes and easily triggered ANR occur.