| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice TestPractice Test
About Exam
hard
Static Synchronized Method Behavior
< Prev
Next >

What does the use of the ‘static synchronized’ keyword in the increment() method ensure in this example?

public class StaticInstanceSync {
    private static int counter = 0;
    
    public static synchronized void increment() {
        counter++;
    }
    
    public void runTask() {
        for(int i = 0; i < 1000; i++) {
            increment();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        StaticInstanceSync sis1 = new StaticInstanceSync();
        StaticInstanceSync sis2 = new StaticInstanceSync();
        Thread t1 = new Thread(() -> sis1.runTask());
        Thread t2 = new Thread(() -> sis2.runTask());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter);
    }
}
A

It ensures that only one thread, across all instances, executes the increment() method at a time, preventing race conditions on the counter variable.

B

It guarantees atomic updates to the counter variable without any performance cost.

C

It mistakenly synchronizes on the instance lock, rendering the static method non-thread-safe.

D

It only synchronizes threads accessing the same instance, so race conditions may occur between different instances.

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