views:

116

answers:

2

if we use singleton pattern in our web application, when free the specified memory that allocated to our class?

+1  A: 

Singletons are most likely implemented using a static variable. End static variables aren't garbage-collected (unless their classloader is garbage collected).

So the memory that's taken by the singleton is never freed automatically because the singleton is never garbage-collected.

You can, however, set the static variable to null. Then I think it will be garbage-collected.

When you stop your container (IIS or whatever) the memory is freed, and when you restart, the singleton is instantiated again.

P.S. It appears I'm talking about Java, but it should be nearly the same in C#

Bozho
if we restart IIS, the instance instantiates again? or we should restart the server for this?
masoud ramezani
it is instantiated again.
Bozho
The memory used is released when the AppDomain that IIS runs your app in is disposed of. I assume that's what happens when you stop IIS.
Martinho Fernandes
+2  A: 

Technical answer: The memory is freed when the AppDomain is unloaded or the process is shut down.

Better answer: The memory is freed whenever the GC decides to free it. You don't know and aren't supposed to care. If your Singleton is tracking unmanaged resources (i.e. file handles, GDI handles, anything other than memory), and you need to release them at any time whatsoever while your application is still "running", then the Singleton needs to provide the necessary methods to do so.

Aaronaught