Java Synchronization for Thread Safety
What potential issue is addressed by synchronizing on the board object in the play() method?
public class GameBoard {
private int[][] board = new int[3][3];
public void play(int row, int col, int player) {
synchronized(board) {
if (board[row][col] == 0) {
board[row][col] = player;
}
}
}
public void printBoard() {
for (int[] row : board) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
GameBoard game = new GameBoard();
Thread t1 = new Thread(() -> game.play(1, 1, 1));
Thread t2 = new Thread(() -> game.play(1, 1, 2));
t1.start();
t2.start();
}
}
A
It automatically makes the printBoard() method thread-safe even when called concurrently.
B
It prevents two threads from marking the same cell simultaneously, thus avoiding a race condition.
C
It prevents deadlock by ensuring that only one thread can access the board at once.
D
It ensures that the board is reallocated safely before any updates occur.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE