0

I have an abstract class which is inherited by classes that run on different threads. do the variables in this abstract class act as shared memory?

public abstract class A
{
   public abstract void foo();

   public boolean bar(){
   {
      List<String> x=new ArrayList();
      x.add("a");
      //some code
   }
}
public class B extends A
{
   @Override
   public void foo()
   {
     //some code
   }
 }
public class C extends A
{
   @Override
   public void foo()
   {
     //some code
   }
   @Override
   public boolean bar()
   {
      List<String> x=new ArrayList();
      x.add("a");
      //some code
   }
 }
public class D extends A
{
   @Override
   public void foo()
   {
     //some code
   }
 }

classes B, C and D run in different threads. however x is behaving like a shared memory for A and B and D. is it the expected behaviour? if yes how can i make it thread specific without overriding?

Parth Srivastav
  • 316
  • 2
  • 13

1 Answers1

0

the x variable is not being shared. It's replicated on any thread that invokes the bar() method. If its content is always the same, you should declare it as static final member variable. That is:

public abstract class A
{
 static final  List<String> x=new ArrayList();

Probably it'd also be a good idea to initialize it through a static initializer: Static initializer in Java

Community
  • 1
  • 1
Andres
  • 10,561
  • 4
  • 45
  • 63