473,320 Members | 2,177 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Singleton and garbage collection

I have some strange behavior on my web server that seems to point to garbage
collection. I have a singleton that tracks web activity on my web site.
The singleton works great, except that it restarts periodically. The web
services have not been restarted and the error log shows no problems. It is
the same problem on 2 different servers, but is worse on the most used
server. On the most used server, it gets restarted 5 to 10 times a day
while the other server it is only restarted every couple of days. We
created a second singleton that gets instantiated at the same time to check
to see if was some web activity causing the restart and we found that it
also gets restarted at the same time as the first one. We also threw in
destructors that log to disk but they don't ever seem to get called.

Is a singlton subject to garbage collection and is there a clean way to
avoid this? All we need is a Singleton that will keep an instance as long
as the application is running.

Here's the singleton we used. What we see in the log file is multiple lines
instantiating the singleton but no destructor calls:

using System;
using System.IO;
using System.Configuration;

namespace ABC.DEF.SingletonTier.Tracking {

public class SingletonWatcher {

private static SingletonWatcher moInstance = null;
private static DateTime moStartTime;

private SingletonWatcher() {
this.WriteToLog("# SingletonWatcher Instantiate
#");
moStartTime = DateTime.Now;
}

~SingletonWatcher() {
try {
this.WriteToLog("# SingletonWatcher Destructor
#");
}catch(Exception) {
}
}

public static SingletonWatcher Instance {
get {
if(moInstance == null) moInstance = new SingletonWatcher();
return moInstance;
}
}

private StreamWriter moLogWriter = null;
public void WriteToLog(string sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.txt";
FileStream oStream = new FileStream(sPath, FileMode.Append);
moLogWriter = new StreamWriter(oStream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moStartTime.ToString(sFormat)+"][Logged:"+DateTime.Now.ToString
(sFormat)+"] " + sMessage;
moLogWriter.WriteLine(sOut);
moLogWriter.Flush();
} catch(Exception) {
}
}
}
}


Nov 16 '05 #1
7 3593
Stephen,

I think that the reason this might be happening is that you might have
simultaneous access to the singleton occuring. Because it is
application-wide, there exists the possibility that you could be checking
for null, and then before the singleton is created, you have another check
against null, which replaces the first.

The same thing applies to the methods on your singleton. Because they
can be accessed concurrently, you should make sure you place lock sections
around code that accesses class-level fields (since they are effectively
static, since they are exposed only through a singleton).

This should rectify your situation.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Stephen Brown" <no****@telusplanet.net> wrote in message
news:BYFBc.1518$0A.24492@localhost...
I have some strange behavior on my web server that seems to point to garbage collection. I have a singleton that tracks web activity on my web site.
The singleton works great, except that it restarts periodically. The web
services have not been restarted and the error log shows no problems. It is the same problem on 2 different servers, but is worse on the most used
server. On the most used server, it gets restarted 5 to 10 times a day
while the other server it is only restarted every couple of days. We
created a second singleton that gets instantiated at the same time to check to see if was some web activity causing the restart and we found that it
also gets restarted at the same time as the first one. We also threw in
destructors that log to disk but they don't ever seem to get called.

Is a singlton subject to garbage collection and is there a clean way to
avoid this? All we need is a Singleton that will keep an instance as long
as the application is running.

Here's the singleton we used. What we see in the log file is multiple lines instantiating the singleton but no destructor calls:

using System;
using System.IO;
using System.Configuration;

namespace ABC.DEF.SingletonTier.Tracking {

public class SingletonWatcher {

private static SingletonWatcher moInstance = null;
private static DateTime moStartTime;

private SingletonWatcher() {
this.WriteToLog("# SingletonWatcher Instantiate
#");
moStartTime = DateTime.Now;
}

~SingletonWatcher() {
try {
this.WriteToLog("# SingletonWatcher Destructor
#");
}catch(Exception) {
}
}

public static SingletonWatcher Instance {
get {
if(moInstance == null) moInstance = new SingletonWatcher();
return moInstance;
}
}

private StreamWriter moLogWriter = null;
public void WriteToLog(string sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.txt";
FileStream oStream = new FileStream(sPath, FileMode.Append);
moLogWriter = new StreamWriter(oStream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moStartTime.ToString(sFormat)+"][Logged:"+DateTime.Now.ToString (sFormat)+"] " + sMessage;
moLogWriter.WriteLine(sOut);
moLogWriter.Flush();
} catch(Exception) {
}
}
}
}

Nov 16 '05 #2

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:%2****************@TK2MSFTNGP10.phx.gbl...
Stephen,

I think that the reason this might be happening is that you might have
simultaneous access to the singleton occuring. Because it is
application-wide, there exists the possibility that you could be checking
for null, and then before the singleton is created, you have another check
against null, which replaces the first.

The same thing applies to the methods on your singleton. Because they
can be accessed concurrently, you should make sure you place lock sections
around code that accesses class-level fields (since they are effectively
static, since they are exposed only through a singleton).

This should rectify your situation.


I agree that the Instance method should be properly synchronized, this
doesn't account for periodic recreation of the singleton throughout the day.
The threading probmem with this code would happen on application startup
only, and only when the first two requests for the singleton come in in very
close succession. Once the singleton is created the code is thread-safe.

I suspect your appdomain is getting recycled.

David
Nov 16 '05 #3
the aspnet_wp process gets recycled every now and then due to a number of reasons, like uptime, #hits, craches etc. it can also get unloaded after staying inactive for x amount of time. all of which will explain why you experience restarts.

"Stephen Brown" wrote:
I have some strange behavior on my web server that seems to point to garbage
collection. I have a singleton that tracks web activity on my web site.
The singleton works great, except that it restarts periodically. The web
services have not been restarted and the error log shows no problems. It is
the same problem on 2 different servers, but is worse on the most used
server. On the most used server, it gets restarted 5 to 10 times a day
while the other server it is only restarted every couple of days. We
created a second singleton that gets instantiated at the same time to check
to see if was some web activity causing the restart and we found that it
also gets restarted at the same time as the first one. We also threw in
destructors that log to disk but they don't ever seem to get called.

Is a singlton subject to garbage collection and is there a clean way to
avoid this? All we need is a Singleton that will keep an instance as long
as the application is running.

Here's the singleton we used. What we see in the log file is multiple lines
instantiating the singleton but no destructor calls:

using System;
using System.IO;
using System.Configuration;

namespace ABC.DEF.SingletonTier.Tracking {

public class SingletonWatcher {

private static SingletonWatcher moInstance = null;
private static DateTime moStartTime;

private SingletonWatcher() {
this.WriteToLog("# SingletonWatcher Instantiate
#");
moStartTime = DateTime.Now;
}

~SingletonWatcher() {
try {
this.WriteToLog("# SingletonWatcher Destructor
#");
}catch(Exception) {
}
}

public static SingletonWatcher Instance {
get {
if(moInstance == null) moInstance = new SingletonWatcher();
return moInstance;
}
}

private StreamWriter moLogWriter = null;
public void WriteToLog(string sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.txt";
FileStream oStream = new FileStream(sPath, FileMode.Append);
moLogWriter = new StreamWriter(oStream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moStartTime.ToString(sFormat)+"][Logged:"+DateTime.Now.ToString
(sFormat)+"] " + sMessage;
moLogWriter.WriteLine(sOut);
moLogWriter.Flush();
} catch(Exception) {
}
}
}
}


Nov 16 '05 #4
> the aspnet_wp process gets recycled every now and then due to a number of
reasons, like uptime, #hits, craches etc.
it can also get unloaded after staying inactive for x amount of time. all

of which will explain why you experience restarts.

If this were the case, I would assume we would see at least a couple of
seconds pause (cache load?) when we access the pages after a restart as is
the case when we manually update the assemblies or modify the Web.config
file. We don't see this. I would also assume an entry in the event log if
the process was recycled, as I see locally sometimes.

Can I assume from the responses that this cannot be a garbage collection
issue?
Nov 16 '05 #5
> ....Because it is
application-wide, there exists the possibility that you could be checking
for null, and then before the singleton is created, you have another check
against null, which replaces the first.
This was the code from our second singleton. The first singleton used the
standard
public static readonly Singleton Instance = new Singleton();
pattern. Either way, there hasn't been a problem between initialization and
the first couple of hours of usage.
The same thing applies to the methods on your singleton. Because they
can be accessed concurrently, you should make sure you place lock sections
around code that accesses class-level fields


This has us puzzled. Is it therefore possible to create a second instance
of the Singleton with concurrent access of a Singleton method, regardless of
how the Singleton is instantiated? ie. using the MSDN Singleton pattern and
not initializing the Singleton instance in any methods, are you saying that
a non-locked method could create a new instance?

Also, is there any possibility of garbage collection causing us this
problem? As mentioned, the singleton can go hours and days fine and then
suddenly another one pops up with no log of the previous one being
destructed?

We originally looked into this as a concurrency problem, but the IIS log
files seem to show little activity at times when the Singleton seems to
restart. We would expect a concurrency problem to show up more often during
peak usages, and not during times when there is no activity like we've seen
(ie. 10 minutes after a web hit and hours before the next one).

Nov 16 '05 #6
Stephen,

Since you are holding an instance, it is not a GC issue (at least, so it
seems).

I hadn't considered the fact that this was in ASP, and as David Browne
and Daniel Jin have pointed out, this can very well be the result of the app
domain being stopped and restarted. Because of this, I would not use a
static level field. Rather, I would use some other means to get your
singleton (through a serviced component, perhaps, or remoting to a service
on the machine that will host the object, etc, etc).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Stephen Brown" <no****@telusplanet.net> wrote in message
news:ijHBc.1527$0A.24604@localhost...
the aspnet_wp process gets recycled every now and then due to a number
of reasons, like uptime, #hits, craches etc.
it can also get unloaded after staying inactive for x amount of time.
all of which will explain why you experience restarts.

If this were the case, I would assume we would see at least a couple of
seconds pause (cache load?) when we access the pages after a restart as is
the case when we manually update the assemblies or modify the Web.config
file. We don't see this. I would also assume an entry in the event log if the process was recycled, as I see locally sometimes.

Can I assume from the responses that this cannot be a garbage collection
issue?

Nov 16 '05 #7
The pause is due to the JIT, as the cache cost should be insignificant
against your app being rejitted.

The best way to determine if your app has been restarted is to use perfmon.
Perfmon is your friend -- the ASP.NET and the per-app ASP.NET Application
perf objects will tell you immediately if you have had a restart when your
singleton is recreated.

--
Mickey Williams
Author, "Microsoft Visual C# .NET Core Reference", MS Press
www.servergeek.com/blogs/mickey

"Stephen Brown" <no****@telusplanet.net> wrote in message
news:ijHBc.1527$0A.24604@localhost...
If this were the case, I would assume we would see at least a couple of
seconds pause (cache load?) when we access the pages after a restart as is
the case when we manually update the assemblies or modify the Web.config
file. We don't see this. I would also assume an entry in the event log if the process was recycled, as I see locally sometimes.

Can I assume from the responses that this cannot be a garbage collection
issue?

Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Saruman | last post by:
Unfortunately I am not able to find a direct answer to this question neither in documentation nor in newsgroups. I have an application biggest part of which is dynamically reloaded in certain...
11
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be...
1
by: Stephen Brown | last post by:
I posted a question yesterday about a Singleton I have, using the standard dotNet pattern, that seems to get recreated several times a day. I turned on my performance counters (thanks to Mickey...
7
by: ThunderMusic | last post by:
Hi, I have a problem regarding singletons in C#. What I would like to do is the following ClassA is a singleton ClassB inherits from ClassA and is also a Singleton there cannot and instance of...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.