| preferred AP College board partner for AP classes
AP Computer Science A/Unit 10: Recursion
Start Practice TestPractice Test
About Exam
hard Solved by 4 students
Thread Safety With AtomicInteger
< Prev
Next >

Why is AtomicInteger preferred over a volatile int in this recursive multithreaded context?

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

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

B

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

C

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

D

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

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