I've got a class I want to use as a singleton by creating a static instance of it. Naturally I also want it to be thread safe.
Assume I am not sharing any private data. But if I am not mistaken, there still remains the problem that when calling a method of a static object instance, variables within methods are shared across threads, and would have unpredictable results.
However, when calling a real static method, a new stack frame is created, so it is thread safe (unto itself) anyway. Again, if I am not mistaken.
Would this pattern for a singleton be thread safe?
class Singleton
{
public object SomeMethod(object arg) {
return Singleton.SomeMethodImpl(arg);
}
private static object SomeMethodImpl(object arg) {
// is in unique stack frame?
object Result;
...
return Result;
}
}
In case you are wondering why I don't just create a static class in the first place - I need to have a singleton that is based on an interface, and has different implementations, as part of a strategy pattern. This doesn't work for static classes.