Shared State in a Recursive Method
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.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE