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 1 students

Shared State in a Recursive Method

Mark
< Prev
Next >

Consider the recursiveFactorial method, which uses a static variable result. Which statement best describes a potential issue with this implementation?

public class SynchronizedRecursive {
    private static int result = 0;
    
    public static int recursiveFactorial(int n) {
        if(n <= 1) return 1;
        synchronized(SynchronizedRecursive.class) {
            result = n * recursiveFactorial(n - 1);
            return result;
        }
    }
    
    public static void main(String[] args) {
        System.out.println(recursiveFactorial(5));
    }
}
A

There is no issue as the shared variable is only used to store the final result which is computed correctly.

B

Using a shared variable can cause incorrect results in a concurrent context, as recursive calls may overwrite its value if invoked by multiple threads.

C

The code will deadlock due to the recursive nature of the synchronized block.

D

The synchronized block entirely prevents any issues, making the use of a shared variable safe in all contexts.

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|