Threading behavior of methods of a class object declared as static member of another class

104 views Asked by At

Recently a colleague of mine came up with a piece of code and asked my opinion regarding thread safety of the code. Below is an example that illustrates the same scenario as the code.

public class classA
{
   public int DoWorkA() 
   { 
       //some logic 
   }
}

public class classB
{
     public static classA objA = new classA();
}

public class classC
{
        int DoWorkC () 
        {

           return classB.objA.DoWorkA();

        }
}

Now if ClassB.objA.DoWorkA() is called simulatenously in different instances of different classes like ClassC, ClassD etc will there be any threading or 'overlap' issues ? Should objA be converted into an instance member ?

2

There are 2 answers

1
BrokenGlass On

Since objA is static there will be just a single instance of classA. That means all threads access the method DoWorkA() on the same instance, it does not mean however that the method call is thread-safe - that entirely depends on the implementation of DoWorkA().

You will still need appropriate logic in DoWorkA to protect from problems that can arise with concurrent access, e.g. the use of locking or thread-safe collections etc.

2
Reed Copsey On

will there be any threading or 'overlap' issues

It depends on what //some logic does. Each call will share the same instance, so DoWorkA would need to be thread safe in order for this to function correctly.

Any data used within //some logic needs proper synchronization for this to be safe.