skip to content

In Jetpack DataStore, why does a second instance on the same file throw IllegalStateException, and how do you share one file across processes?

level: seniorimportance: should knowfreq 38%

answer

  1. one active instance per file
  2. registry of active file paths
  3. fails on first read or write
  4. active while its scope is active
  5. MultiProcessDataStoreFactory in every process

basics

~20 s

DataStore allows one active instance per file in a process; a second one fails on its first read or write with "There are multiple DataStores active for the same file". Across processes, every process must use MultiProcessDataStoreFactory, one instance each.

solid answer

~50 s

DataStore keeps one in-memory cache and one write queue per instance, so two instances on one file would each believe they own it and could overwrite each other. It enforces this: the file storage records each active file path, and a second instance fails on its first read or write with an `IllegalStateException`, "There are multiple DataStores active for the same file". An instance counts as active until its scope is cancelled. Typical causes are a delegate or factory call inside a ViewModel, Activity, composable or test. The fix is one instance per file: a top-level delegate or a single DI-provided instance. A second process is invisible to that check, so for a file shared with a service in another process you use `MultiProcessDataStoreFactory.create` in every process, available since 1.1.0, and never mix it with a single-process store.

code

kotlin · 25 lines
kotlin
import android.app.Application
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.lifecycle.AndroidViewModel

// Bug: every ReaderViewModel builds its own DataStore on the same file.
// The second instance throws IllegalStateException on its first read or write,
// because the first store's default scope is never cancelled.
class BrokenReaderViewModel(app: Application) : AndroidViewModel(app) {
    private val settings: DataStore<Preferences> =
        PreferenceDataStoreFactory.create {
            app.preferencesDataStoreFile("reader_settings")
        }
}

// Fix: one top-level delegate, shared by every caller in the process.
val Context.readerSettings: DataStore<Preferences> by preferencesDataStore(name = "reader_settings")

class ReaderViewModel(app: Application) : AndroidViewModel(app) {
    private val settings: DataStore<Preferences> = app.readerSettings
}

go deeper

for a junior

Recall the rule: one DataStore instance per file in a process, created once by a top-level delegate or a singleton.

for a middle

Explain why two instances break the guarantees: each has its own cache and write queue, so updates are lost and reads go stale.

for a senior

Diagnose the IllegalStateException from its message: lazy failure on first read or write, active-until-scope-cancelled, and duplicates from ViewModels, composables or tests.

for a principal

Decide when cross-process access is worth MultiProcessDataStoreFactory's coordination, and set a rule that every store is provided as an application singleton.

## The rule The Android guide puts it first among its rules for using DataStore correctly: **never create more than one instance of DataStore for a given file in the same process**. Each instance owns an in-memory cache of the current value and a serialized write queue. Two instances on one file would each serialize only their own writes, cache values the other one has overwritten, and lose updates silently. ## How DataStore enforces it The file-backed storage keeps a process-wide set of **active file paths**. When an instance opens its connection to the file, the storage checks that set: - if the canonical path is already present, it fails with an `IllegalStateException`: "There are multiple DataStores active for the same file: <path>. You should either maintain your DataStore as a singleton or confirm that there is no two DataStore's active on the same file (by confirming that the scope is cancelled)." - otherwise it records the path and proceeds. Two details matter when you diagnose it: 1. **The failure comes on the first read or write**, not when the second instance is created, because the file path is resolved lazily. A crash in `data.first()` or `edit` can point to a store built somewhere else entirely. 2. **An instance is active as long as its scope is active.** When its `CoroutineScope` is cancelled, the store closes its connection and removes the path, so a new instance can open the file. ## Where duplicates come from - A `preferencesDataStore` or `dataStore` delegate declared **inside a class** rather than at the top level: every object gets its own delegate. - `PreferenceDataStoreFactory.create` or `DataStoreFactory.create` called in a **ViewModel, Activity, Worker or composable**, so each new instance builds a store on the same file. - Two top-level delegates in different files that happen to use the **same name**. - **Tests** that build a fresh store per test on the same file without cancelling the previous store's scope. Create each test store with a scope the test cancels, such as the test's background scope. The fix is always one instance per file per process: a top-level delegate, or a single instance provided as an application-wide singleton by your dependency injection (for example a Hilt `@Singleton` provider). ## Sharing a file across processes A service declared with `android:process=":sync"` runs in a **separate process** with its own memory, so the in-process check cannot see the app's instance. Two single-process stores on one file in two processes do not throw, but neither coordinates with the other: observers in one process miss the other's writes and concurrent updates are not serialized. For that case DataStore provides **`MultiProcessDataStoreFactory`**, available since 1.1.0 and no longer experimental: | | Single-process store | Multi-process store | |---|---|---| | Created with | `dataStore` / `preferencesDataStore` delegates, `DataStoreFactory.create` | `MultiProcessDataStoreFactory.create` | | Coordination | In-process only | Cross-process file lock and change notifications | | Instances | One per file per process | Still one per file **per process** | The guide lists what the multi-process store guarantees: reads return only persisted data, read-after-write consistency, serialized writes, and reads are never blocked by writes. Two rules still apply: - create it with `MultiProcessDataStoreFactory` in **every** process that touches the file, and do not mix single-process and multi-process stores for the same file; - each process still holds **exactly one** instance; the multi-process factory does not lift the in-process rule. ## Owning the single instance The cleanest pattern is to make the store an **application-wide object** and pass it down: - a top-level `preferencesDataStore` or `dataStore` delegate on `Context`, used only from a repository; - or a factory call inside a dependency injection provider scoped to the application, so the graph builds it exactly once; - never a factory call in a class whose instances come and go with screens, workers or compositions. If a store genuinely must be replaced at runtime, cancel the old one's `CoroutineScope` first; DataStore 1.2 has no close method, and cancelling the scope is what releases the file. ## Diagnosing it in production 1. Read the path in the exception message to identify the file. 2. Search for every place that builds a store for that file name, including tests and DI modules. 3. Check whether the owning class can exist twice: two ViewModels, an Activity recreated on rotation, a recomposed composable. 4. Move creation to one top-level delegate or one singleton, or cancel the old scope before creating a replacement.

  • How do you write tests that each need a fresh DataStore on the same file name?
    Give each test's store a scope that the test cancels when it ends, such as the coroutine test's `backgroundScope`, and use a temporary folder for the file. Cancelling the scope closes the connection and frees the path, so the next test's instance can open it without the `IllegalStateException`.
  • Does MultiProcessDataStoreFactory allow two instances on one file inside the same process?
    No. Its documentation repeats the rule: never create more than one instance for a given file in the same process, or reads and updates throw `IllegalStateException`. It adds coordination between processes, each of which still holds exactly one instance for the file.

  • DataStore throws as soon as the second instance is constructed.
  • Two instances on one file are fine as long as only one of them writes.
  • Cancelling a store's scope has no effect on the one-instance check.
  • A separate android:process service is caught by the same duplicate check.
  • MultiProcessDataStoreFactory lets each process hold several instances per file.

Assumes DataStore 1.2.1; MultiProcessDataStoreFactory shipped in the 1.1.0 release, and its experimental annotation was removed in 1.1.0-alpha07.