devanalyst
devanalyst

Reputation: 1478

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

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 ?

Upvotes: 1

Views: 94

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564891

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.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 161002

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.

Upvotes: 2

Related Questions