Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java thread safe recursion

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.

like image 493
user710818 Avatar asked Jul 01 '26 11:07

user710818


2 Answers

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:

  • The arguments to the constructor of CRecursion must not be shared across multiple threads. If they are shared, then the following point becomes relevant.
  • Any objects that are shared across multiple threads, must not be accessed (read from or written to) in the recursion routine.
  • The recursion routine uses local variables that are confined to the current stack frame. The routine must not access any other shared storage area (other than the Java call stack) to exchange data between invocations.
like image 119
Vineet Reynolds Avatar answered Jul 03 '26 02:07

Vineet Reynolds


  1. Are you sharing any data between threads?

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.

like image 35
Swaranga Sarma Avatar answered Jul 03 '26 01:07

Swaranga Sarma