Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
About Exam
hard

Java Thread Safety and Synchronized Methods

Mark
< Prev
Next >

Which statement accurately describes the thread safety of the provided program?

public class SyncCounter {
    private int count = 0;
    public synchronized void increment() { count++; }
    public int getCount() { return count; }
}

public class Worker extends Thread {
    private SyncCounter counter;
    public Worker(SyncCounter counter) { this.counter = counter; }
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        SyncCounter c = new SyncCounter();
        Thread t1 = new Worker(c);
        Thread t2 = new Worker(c);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count is: " + c.getCount());
    }
}
A

The program safely synchronizes counter increments, preventing race conditions.

B

A race condition exists because the getCount() method is unsynchronized.

C

The counter variable could be updated inconsistently because it isn’t declared as volatile.

D

Deadlock is possible due to nested synchronized calls.

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.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|