if we use singleton pattern in our web application, when free the specified memory that allocated to our class?
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#
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.