Skip to content

Implement press, and hold switch actions#2

Merged
enaboapps merged 1 commit into
devfrom
switch-actions
Jan 3, 2024
Merged

Implement press, and hold switch actions#2
enaboapps merged 1 commit into
devfrom
switch-actions

Conversation

@enaboapps
Copy link
Copy Markdown
Collaborator

No description provided.

@enaboapps enaboapps merged commit 29a3938 into dev Jan 3, 2024
@enaboapps enaboapps deleted the switch-actions branch January 3, 2024 13:46
OwenMcGirr added a commit that referenced this pull request Jan 2, 2026
Fixed race condition in getInstance() where multiple threads could create
multiple database instances due to incomplete double-checked locking.

**Problem:**
The original code only checked INSTANCE before entering synchronized:
```kotlin
return INSTANCE ?: synchronized(this) {
    val instance = Room.databaseBuilder(...).build()
    INSTANCE = instance
    instance
}
```

**Race Condition Scenario:**
1. Thread A checks INSTANCE == null
2. Thread B checks INSTANCE == null
3. Thread A enters synchronized, creates DB instance #1
4. Thread B waits for lock
5. Thread B enters synchronized, creates DB instance #2 (BUG!)
6. Two database instances exist, causing corruption

**Solution:**
Added second null-check inside synchronized block (double-checked locking):
```kotlin
return INSTANCE ?: synchronized(this) {
    // Second check AFTER acquiring lock
    INSTANCE ?: Room.databaseBuilder(...).build().also { INSTANCE = it }
}
```

**How It Works:**
1. Thread A checks INSTANCE == null (first check)
2. Thread B checks INSTANCE == null (first check)
3. Thread A enters synchronized, checks again (second check), creates instance
4. Thread B waits for lock
5. Thread B enters synchronized, checks again (second check), sees INSTANCE != null
6. Thread B returns existing instance - no duplicate!

**Thread Safety:**
- @volatile ensures INSTANCE writes are visible across threads
- synchronized prevents concurrent creation
- Double-check minimizes synchronization overhead (only on first access)

This is the standard double-checked locking pattern for thread-safe
singleton initialization.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants