EDIT: Ok, it works now. I don’t know exactly what was the worst problem, but i haven’t done some locking which was needed to avoid race conditions. Also i added the “volatile” key-word to the deklaration of the instance variable of the singleton.
if i have some threads running and in one thread i access a singleton (which was maybe created in another thread), i get a fresh “singleton” in terms of that the constructor of the singleton is called for every thread who access it in his memory space the first time? Have i understood this right?
The problem is in my application i have a singleton created by the main thread. If i then call Singleton.Instance.somemethod(…) i get always null pointer exceptions or empty lists, even if the lists were created and filled in the main thread?
Is there a way to handle that problem, so that i can use the same instance of the singleton in all threads running? Some way of synchronizing the whole instance?
Thank you.
EDIT: Sorry lacking some really important information. I am using C# and the .NET Framework 4.0 under Visual Studio 2010 Professional.
I create the Singleton this way:
static readonly object _padlock = new object();
public static StaticAnalyzer Instance
{
get
{
lock (_padlock)
{
if (_instance == null)
{
_instance = new StaticAnalyzer();
}
return _instance;
}
}
}
In the background every thread has its own virtual memory space or not? So if i create the singleton in the main thread and then in create some worker threads with the task.factory and the worker threads call the instance, why does they get the real singleton? because of the static keyword?
No, a singleton (if implemented correctly) will be just one for all the threads. Like
System.DBNull. Otherwise it’s not a singleton. You must have a mistake in your code somewhere.