I have nested class CRecursion which has method that do recursion. This CRecursion created in many threads. Is safe call from thread method from main class? Thanks.
class A {
method1() {....}
for(int i=0;i<100;i++){
execute(new CRecursion(...))
}
protected CRecursion {
calculate (par){
if (some_condition) {
calculate(par1)
} else {
String s=method1(value);
.....
}
}
....
}
Variable value is Object. But internal for each method.
If the objects used by the recursive routine are confined to the same thread, then yes, the recursive routine is thread-safe. It would help to read this related StackOverflow question on thread confinement and it's impact on thread-safety.
In this particular case (with the code that you've posted), you'll need to ensure that:
CRecursion must not be shared across multiple threads. If they are shared, then the following point becomes relevant.If answer to the above question is NO, then the call is implicitly thread safe.
If you are worried that local variables will be garbled via multiple call to the same method from different threads, then you are mistaken. Each invocation of a method creates its own seperate copy of those variables.
In essence if you are not sharing any data your call is thread safe.
Technically, you can still share data and be thread safe, the only condition is that all access to the shared data must be a read operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With