SharedPreferences vs DataStore: The Hidden Lock That Freezes Android Apps
If your app relies on apply() for frequent config writes, the ANR you're chasing may actually live in onStop() and other lifecycle callbacks, not where you called it. Moving to DataStore eliminates the lock and the full-file rewrite, and Compose/MVI apps get reactive updates without polling.
SharedPreferences (SP) freezes and ANRs even when you use apply(). SP's SharedPreferencesImpl uses a global lock, so every read and write contends for it. Worse, the underlying XML file cannot be partially updated: changing one boolean re-serializes the entire configuration and rewrites the whole file. When a background write holds the lock, the main thread blocks and can trigger an ANR. apply() does not solve this; it updates memory immediately and queues the disk write, but Android forces pending writes to finish at lifecycle boundaries like onStop(), so the freeze just moves to a less obvious spot.
DataStore abandons locks. It uses an Actor model: all modifications are sent as messages through a Channel, and a single coroutine processes them serially, which eliminates lock contention. Writes are atomic: it writes a temporary file and then replaces the official one, preventing corruption. Reads are cached in memory and updates are pushed via Kotlin Flow, fitting Compose and MVI. The article compares Preferences DataStore (key-value, easy migration) with Proto DataStore (Protocol Buffers, strong typing). The author recommends DataStore for new projects and targeted migration of SP-heavy, high-frequency paths in existing apps.
apply() is not async persistence; it's deferred blocking that surfaces at lifecycle boundaries, which is why ANR reports can be near impossible to reproduce.
Serializing all writes through one coroutine makes ordering deterministic but caps throughput; for apps with constant high-frequency writes, the Channel and scheduling overhead can offset the lock-free benefit.
Preferences DataStore keeps the same type-unsafe key-value model as SP; migrating to it buys concurrency stability, not a better data contract, whereas Proto DataStore requires schema design upfront.