473,856 Members | 1,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Configur ation;

namespace ABC.DEF.Singlet onTier.Tracking {

public class SingletonWatche r {

private static SingletonWatche r moInstance = null;
private static DateTime moStartTime;

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

~SingletonWatch er() {
try {
this.WriteToLog ("# SingletonWatche r Destructor
#");
}catch(Exceptio n) {
}
}

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

private StreamWriter moLogWriter = null;
public void WriteToLog(stri ng sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.t xt";
FileStream oStream = new FileStream(sPat h, FileMode.Append );
moLogWriter = new StreamWriter(oS tream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moSt artTime.ToStrin g(sFormat)+"][Logged:"+DateTi me.Now.ToString
(sFormat)+"] " + sMessage;
moLogWriter.Wri teLine(sOut);
moLogWriter.Flu sh();
} catch(Exception ) {
}
}
}
}


Nov 16 '05 #1
7 3621
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.co m

"Stephen Brown" <no****@teluspl anet.net> wrote in message
news:BYFBc.1518 $0A.24492@local host...
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.Configur ation;

namespace ABC.DEF.Singlet onTier.Tracking {

public class SingletonWatche r {

private static SingletonWatche r moInstance = null;
private static DateTime moStartTime;

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

~SingletonWatch er() {
try {
this.WriteToLog ("# SingletonWatche r Destructor
#");
}catch(Exceptio n) {
}
}

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

private StreamWriter moLogWriter = null;
public void WriteToLog(stri ng sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.t xt";
FileStream oStream = new FileStream(sPat h, FileMode.Append );
moLogWriter = new StreamWriter(oS tream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moSt artTime.ToStrin g(sFormat)+"][Logged:"+DateTi me.Now.ToString (sFormat)+"] " + sMessage;
moLogWriter.Wri teLine(sOut);
moLogWriter.Flu sh();
} catch(Exception ) {
}
}
}
}

Nov 16 '05 #2

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:%2******** ********@TK2MSF TNGP10.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.Configur ation;

namespace ABC.DEF.Singlet onTier.Tracking {

public class SingletonWatche r {

private static SingletonWatche r moInstance = null;
private static DateTime moStartTime;

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

~SingletonWatch er() {
try {
this.WriteToLog ("# SingletonWatche r Destructor
#");
}catch(Exceptio n) {
}
}

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

private StreamWriter moLogWriter = null;
public void WriteToLog(stri ng sMessage) {
try {
if(moLogWriter == null) {
string sPath = "SingletonLog.t xt";
FileStream oStream = new FileStream(sPat h, FileMode.Append );
moLogWriter = new StreamWriter(oS tream);
}
string sFormat = "dd-MM-yy HH:mm:ss";
string sOut =
"[Instance:"+moSt artTime.ToStrin g(sFormat)+"][Logged:"+DateTi me.Now.ToString
(sFormat)+"] " + sMessage;
moLogWriter.Wri teLine(sOut);
moLogWriter.Flu sh();
} 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.co m

"Stephen Brown" <no****@teluspl anet.net> wrote in message
news:ijHBc.1527 $0A.24604@local host...
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****@teluspl anet.net> wrote in message
news:ijHBc.1527 $0A.24604@local host...
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
7241
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 circumstances - kind of webstart, but dynamic (you have to restart webstart to get a new version of an application) and without a GUI. The problem is that I have some singletons among my objects. Turns out that garbage collector has some trouble...
11
2177
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 possible to extend the Singleton pattern to handle this? Assuming that my Customer class follows the Singleton pattern (particularly Skeet's 4th version) I'm thinking if I add private static SomeCollectionType customers;
1
1417
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 William's post yesterday) and my Singleton restarting happens at the same time as an application restart. Now it's pretty clear it has nothing to do with garbage collection and it makes sense that application restart would destroy my singleton. ...
7
1433
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 ClassA and an instance of ClassB, there must be only one of one or the other... Is there a way to do it? or it's simply not possible?
0
9916
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9762
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11057
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10696
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10782
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10384
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7932
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7094
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
3201
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.