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

Thread Safety With AtomicInteger

Mark
< Prev
Next >

Consider the following AtomicRecursive class. Why is AtomicInteger the appropriate choice for the counter variable instead of a volatile int?

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicRecursive {
    private static AtomicInteger counter = new AtomicInteger(0);
    
    public static void recursiveIncrement(int n) {
        if(n <= 0) return;
        counter.getAndIncrement();
        new Thread(() -> recursiveIncrement(n - 1)).start();
    }
    
    public static void main(String[] args) throws InterruptedException {
        recursiveIncrement(5);
        Thread.sleep(1000);
        System.out.println("Counter: " + counter.get());
    }
}
A

Both volatile int and AtomicInteger offer the same thread safety for compound operations.

B

AtomicInteger is only used to improve performance, not for thread-safety.

C

AtomicInteger provides atomic operations for increments, ensuring thread-safety for compound actions, which volatile does not guarantee.

D

A volatile int automatically handles atomic increments, making AtomicInteger redundant.

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|