Olivier
Olivier

Reputation: 31

Instanciating a thread-safe class from a non thread-safe class

In a not thread-safe class you must avoid to use class variables at they can be shared by different threads end executing contexts. But if you instanciate an external class which itself has class variables, will these be thread-safe ?

In this example, is there any risk to share the counter variable between threads ?

class MyNotThreadSafeClass()
{
   private integer sharedvariable;
   public void callAnOtherClass()
   {
      myClass o = new myClass();
      System.out.println(o.increment(counter));
   }
}

class myClass()
{
   private integer counter;
   public void increment() { return(counter++); }  
}

Thank you if you have an idea (documentation is not very clear in this thread-safe topic).

Upvotes: 0

Views: 56

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328594

This works since you never pass o to another thread. So no other thread can ever access this instance.

The general pattern is: If you share one instance between several threads, then you need to have some sort of synchronization.

If you don't share an instance, it doesn't matter if there are more threads.

Upvotes: 1

Related Questions