Is it possible to implement Singleton Pattern in multithread program? - multithreading

There is a Windows.Forms.Timer in my project. In the Timer.Tick Method Handler I create an instance of Manager class (My Own Class) And In Manager Constructor I create some threads and store them in a dictionary. The dictionary located in a class named TransManager which implemented with singleton pattern.
public class TransManager {
private static volatile TransManager _Instance;
public static TransManager Instance
{
get
{
lock (syncRoot)
{
if (_Instance == null)
_Instance = new TransManager();
}
return _Instance;
}
}
}
I implemented the class TransManager because I need to have all created threads which produced from different instance of Manager class in same place.
The problem is when a new instance of Manager adds threads in the dictionary the last threads are gone!
Note: When I create All threads within an instance of Manager class then all thread can share the dictionary safe. According to this can I say it is possible to singleton across threads?
I checked; There is no Dictionary.Clear() in my code!
I hope the problem was clear! Ask me if it is not.
Thank you.

Related

Garbage collection for instances within singleton class

I have a singleton class whose instance is alive throughout the lifespan of my application. From one of the singelton instance method I am creating instance of a Runnable thread and executing it. Will the runnable thread instance become a candidate for garbage collection after its execution or will it remain in heap forever since my singleton instance is always alive?
Eg: In the example below I create a new instance of MyRunnable class each time MySingleton.getInstance().runMyThread() is called. Will these MyRunnable instances be considered for garbage colletion once done with the run() method is completely executed and over?
public class MySingleton
{
private MySingleton instance = null;
private MySingleton() {}
public static MySingleton getInstance()
{
if(instance == null)
{
instance = new MySingleton();
}
}
public void runMyThread()
{
Thread thread = new Thread(new MyRunnable()); //MyRunnable implements Runnable
thread.start();
}
}
In general an object will be a candidate for garbage collection when
it is no longer in scope and
nothing references it.
In this scenario, assuming nothing is referencing the Thread object after it finishes execution it will become a candidate for garbage collection. In your example, your singleton instances does not contain any references to the Thread object - it calls runMyThread() which creates a new Thread object and starts it. The Thread object's scope is contained to the runMyThread() method.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

Confusion with IDisposable

I have some nagging doubts about the correct way to implement IDisposable. Consider the following scenario...
public class Foo : IDisposable {...}
public class Bar : IDisposable {
private bool disposed = false;
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public Bar(Foo foo) {
this.MyFoo = foo;
}
~Bar() {
Dispose(false);
}
protected virtual void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
if (MyFoo != null) {
this.MyFoo.Dispose();
this.MyFoo = null;
}
}
this.disposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
My questions are:
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
The above pattern seems to crop up quite a lot (particularly with DI), but I don't seem to be able to find a concrete example of the correct way to structure this.
Refer to Excellent MSDN article
Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
Yes it should. Otherwise also, Dispose will be called. But that will increase life of object by atleast 1 generation. This is due to the finalizer in the class definition. Refer to the article link above.
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
It is responsibility of caller (more specifically the class which has created an instance) to call the Dispose method.
~Bar() {
Dispose(false);
}
Whenever you find yourself writing code like this, take a deep breath first and ask "do I actually need a finalizer?" It is extremely rare that you need one, a finalizer is only required when you take ownership of an unmanaged resource yourself.
The first litmus test is "does the finalizer actually do anything?" That's clear if you follow the code. It calls Dispose(false) and that code only does something when the argument is true. What follows is that you don't need a finalizer. This is entirely normal, finalizers is something that Microsoft worries about. They wrote the .NET framework classes that wrap an unmanaged resource. FileStream, Socket, etcetera. And above all, the SafeHandle classes, designed to wrap operating system handles. They have their own finalizer, you don't rewrite one yourself.
So without a finalizer, the code entirely collapses to the simple and correct implementation, you only need to call the Dispose() method of any disposable objects you store yourself:
public class Bar : IDisposable {
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public void Dispose() {
MyFoo.Dispose();
}
}

java:singleton, static variable and thread safety

class MyClass
{
private static MyClass obj;
public static MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
In the above java code sample, because obj is a static variable inside the class,
will getInstance still be non-thread safe? Because static variables are shared by all threads, 2 simultaneous threads shall be using the same object. Isnt it?
Vipul Shah
Because static variables are so widely shared they are extremely un-thread safe.
Consider what happens if two threads call your getInstance at the same time. Both threads will be looking at the shared static obj and both threads will see that obj is null in the if check. Both threads will then create a new obj.
You may think: "hey, it is thread safe since obj will only ever have one value, even if it is initialized multiple times." There are several problems with that statement. In our previous example, the callers of getInstance will both get their own obj back. If both callers keep their references to obj then you will have multiple instances of your singleton being used.
Even if the callers in our previous example just did: MyClass.getInstance(); and didn't save a reference to what MyClass.getInstance(); returned, you can still end up getting different instances back from getInstance on those threads. You can even get into the condition where new instances of obj are created even when the calls to getInstance do not happen concurrently!
I know my last claim seems counter-intuitive since the last assignment to obj would seem to be the only value that could be returned from future calls to MyClass.getInstance(). You need to remember, however, that each thread in the JVM has its own local cache of main memory. If two threads call getInstance, their local caches could have different values assigned to obj and future calls to getInstance from those threads will return what is in their caches.
The simplest way to make sure that getInstance thread safe would be to make the method synchronized. This will ensure that
Two threads can not enter getInstance at the same time
Threads trying to use obj will never get a stale value of obj from their cache
Don't try to get clever and use double checked locking:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Good explanation can be found here:
http://en.wikipedia.org/wiki/Singleton_pattern
The wiki article highlights various thread-safe approaches along with some of their pros and cons.
in this case getInstance() is not thread-safe, even if you use static variable. only synchronization makes this thread-safe.
The following example shows a weird thread save modified single ton pattern which supports generics as well.
To have it just thread save and synchronization save just take the synchronized block and the transient and volatile keywords.
Notice, that there is a double check, the synchronized block is inside an if. This brings more performance, because synchronized is expensive.
Of course for a real singleton do not use maps, I said it is a modified one.
public class Edge<T> {
#SuppressWarnings({"unchecked"})
private static transient volatile HashMap<Object,HashMap<Object, Edge>> instances = new HashMap<Object, HashMap<Object,Edge>>();
/**
* This function is used to get an Edge instance
* #param <T> Datatype of the nodes.
* #param node1, the source node
* #param node2, the destination node
* #return the edge of the two nodes.
*/
#SuppressWarnings({"unchecked"})
public static <T> Edge<T> getInstance(T node1, T node2){
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
synchronized (Edge.class) {
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
Edge<T> edge = new Edge<T>(node1, node2);
if(!instances.containsKey(node1)){
instances.put(node1, new HashMap<Object, Edge>());
}
instances.get(node1).put(node2, edge);
}
}
}
return (Edge<T>)instances.get(node1).get(node2);
}
public class Singleton{
private static transient volatile Singleton instance;
public static Singleton getInstance(){
if(instance==null)synchronized(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
return instance;
}
private Singleton(){
/*....*/
}
}
Page 182:
http://books.google.com/books?id=GGpXN9SMELMC&printsec=frontcover&dq=design+patterns&hl=de&ei=EFGCTbyaIozKswbHyaiCAw&sa=X&oi=book_result&ct=result&resnum=2&ved=0CDMQ6AEwAQ#v=onepage&q&f=false
Think this can be tagged as answered now.
class MyClass
{
private static MyClass obj;
private MyClass(){
// your initialization code
}
public static synchronized MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
I'll agree with #Manoj.
I believe the above will be one of the best methods to achieve singleton object.
And synchronization makes the object thread safe.
Even, it's static :)

Threading from within a class with static and non-static methods

Let's say I have
class classA {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
class classB {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
static void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?
Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB?
Does again the static really change nothing in this case?
Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.
In this case there is no functional difference. Each thread gets it's own stack
Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.
Each thread would get it's own stack. There is no functional difference that I can tell between the two.
The only difference (obviously) is that the static version would be unable to access member functions/variables.

Resources