Skip to content

fix: DataStore IllegalStateException at FileStorage.createConnection (multiple active instances) #104

@magisk317

Description

@magisk317

Background

Google Play 线上崩溃出现 java.lang.IllegalStateException,堆栈指向:

  • androidx.datastore.core.FileStorage.createConnection(FileStorage.java:52)
  • 触发链路:SmsCodeApplication.syncPreferences -> AppPreferencesDataStore.syncToSharedPrefs -> getBoolean/getString/...

Root Cause

AppPreferencesDataStore.getInstance(context) 的实现存在并发竞态:

  • 当前实现:INSTANCE ?: synchronized(this) { create + assign }
  • 问题:进入 synchronized 后未做二次判空,多个线程可能先后创建同一路径 DataStore 实例
  • DataStore 1.2.0 会对同一路径多活实例直接抛 IllegalStateException

Impact

  • 线上版本:3.1.4(Play vitals 已出现)
  • 场景:应用启动或并发访问偏好时

Proposed Fix

  1. getInstance 改为标准双重检查(锁内二次判空)
  2. 使用 context.applicationContext 防止非必要的 Context 变化
  3. 增加并发单元测试,验证只会创建一个实例

Acceptance Criteria

  • 启动流程不再触发 FileStorage.createConnection 的 IllegalStateException
  • 并发访问 getInstance 时只创建一个 DataStore 实例
  • 提交信息引用 issue 并自动关闭

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions