| preferred AP College board partner for AP classes
AP Computer Science A/Unit 8: 2D Array
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Java Synchronization for Thread Safety
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy