| 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
< Prev
Next >

What potential issue might arise from using the shared variable ‘result’ in this recursive method?

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 synchronized block entirely prevents any issues, making the use of a shared variable safe in all contexts.

D

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

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