Are you taking CLEP classes? Try clep.ai
| 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

Mark
< Prev
Next >

Consider the following code. What is the effect of declaring the increment method as static synchronized?

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 only synchronizes threads accessing the same instance, so race conditions may occur between different instances.

B

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

C

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

D

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

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|