š® Multiplayer Game Sync (e.g., "Among Us" Style) Concurrency Problem
Let's model the synchronization challenges in a social deduction game like Among Us, where:
10-15 players (threads) interact in real-time
Shared state: Player positions, tasks, voting, emergency meetings
Critical requirements:
No two players can report a body simultaneously
Emergency meetings must serialize discussions
Task progress must be atomic
Deadlock-free voting
š” Solution Approaches
Synchronized Everything
This is the simplest way to make your multiplayer game thread-safe, perfect for beginners learning concurrency. Let's break it down completely.
public class Game {
// Shared game state
private int playersOnline = 0;
private boolean gameStarted = false;
// All methods are synchronized
public synchronized void playerJoin() {
playersOnline++;
}
public synchronized void startGame() {
if (playersOnline >= 4) {
gameStarted = true;
}
}
}
What "synchronized" Actually Does
Lock Acquisition: When a thread enters any synchronized method:
It acquires the object's intrinsic lock (also called the monitor lock)
Other threads must wait if the lock is held
Memory Visibility:
When the lock is released, all changes become visible to other threads
When the lock is acquired, it sees the latest changes
Atomic Execution:
- The entire method runs without interruption from other threads
Test Cases
1. Normal Operation (Single Thread)
Scenario: One player joins the game
Expected: Counter increments correctly
Game game = new Game();
game.playerJoin();
assert game.getPlayersOnline() == 1; // Passes
2. Concurrent Joins (Race Condition Prevented)
Scenario: Two players join simultaneously
Expected: Counter shows 2 without corruption
Game game = new Game();
Thread t1 = new Thread(() -> game.playerJoin());
Thread t2 = new Thread(() -> game.playerJoin());
t1.start();
t2.start();
t1.join();
t2.join();
assert game.getPlayersOnline() == 2; // Always passes
3. Mixed Operations (Join + Start Game)
Scenario: One joins while another tries to start game
Expected: Game starts only if ā„4 players
// ā Without synchronization:
if (playersOnline >= 4) { // Race condition
gameStarted = true;
}
