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 ?
Since
objAis static there will be just a single instance ofclassA. That means all threads access the methodDoWorkA()on the same instance, it does not mean however that the method call is thread-safe - that entirely depends on the implementation ofDoWorkA().You will still need appropriate logic in
DoWorkAto protect from problems that can arise with concurrent access, e.g. the use of locking or thread-safe collections etc.