473,721 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is Singleton collection of Singletons possible??

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 SomeCollectionT ype customers;

and then change the factory to something like

public static GetCustomer(Gui d customerID)
{
// check collection and return existing instance if found
// create new instance and return if not
}

I think I have my mind around the static and singleton concepts, but need to
make sure.
Nov 15 '05 #1
11 2168
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
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?
Sort of - it would then be called the Factory pattern though :)
Assuming that my Customer class follows the Singleton pattern (particularly
Skeet's 4th version) I'm thinking if I add

private static SomeCollectionT ype customers;

and then change the factory to something like

public static GetCustomer(Gui d customerID)
{
// check collection and return existing instance if found
// create new instance and return if not
}

I think I have my mind around the static and singleton concepts, but need to
make sure.


That would be fine - but for thread-safety you should basically have a
lock which is acquired *every* time GetCustomer is called. The fourth
singleton pattern isn't really much use to you here. The second pattern
is much closer to what you'd need to use.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Yeah but I would need the Factory to be a Singleton also or it defeats the
purpose. So I need a GetFactory() and then a GetCustomer() I guess.

As to the locking... help me sort this out in my head. The problem is two
threads could call GetCustomer() right? Since that isn't addressed by the
Singleton nature of the factory itself the locks are required.

So I could follow the 4th pattern for the factory itself and then use the
locks within GetCustomer(). Right? Not that the locking in the overall
pattern probably matters much at that point since I'm going to be locking
left and right in the other method anyway.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
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?


Sort of - it would then be called the Factory pattern though :)
Assuming that my Customer class follows the Singleton pattern (particularly Skeet's 4th version) I'm thinking if I add

private static SomeCollectionT ype customers;

and then change the factory to something like

public static GetCustomer(Gui d customerID)
{
// check collection and return existing instance if found
// create new instance and return if not
}

I think I have my mind around the static and singleton concepts, but need to make sure.


That would be fine - but for thread-safety you should basically have a
lock which is acquired *every* time GetCustomer is called. The fourth
singleton pattern isn't really much use to you here. The second pattern
is much closer to what you'd need to use.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #3
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
Yeah but I would need the Factory to be a Singleton also or it defeats the
purpose. So I need a GetFactory() and then a GetCustomer() I guess.
Well, the factory methods themselves needn't be part of an instance -
you don't need to have a separate class. Any reason not just to have a
static GetCustomer method?
As to the locking... help me sort this out in my head. The problem is two
threads could call GetCustomer() right?
Yes.
Since that isn't addressed by the
Singleton nature of the factory itself the locks are required.
Yes.
So I could follow the 4th pattern for the factory itself and then use the
locks within GetCustomer(). Right?
Yes, if you want to.
Not that the locking in the overall
pattern probably matters much at that point since I'm going to be locking
left and right in the other method anyway.


Right.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
Yes I think I see your point. There's no need for there to ever be an
instance of the factory, as it's only purpose is to expose the static
GetCustomer() (in a Singleton way, of course).

I think I understand that while I could be assured there is only one static
collection, multiple threads calling GetCustomer() could be adding, objects
to it, which would most likely result in a mess. In other words, it's the
fact that my main Singleton object is a collection type, which is by
definition continually changing, that's the problem.

But it appears maybe Microsoft is ahead of me. This is from the Thread
Safety section for HybridDictionar y:
"Public static (Shared in Visual Basic) members of this type are safe for
multithreaded operations. Instance members are not guaranteed to be
thread-safe.

This implementation does not provide a synchronized (thread-safe) wrapper
for a HybridDictionar y, but derived classes can create their own
synchronized versions of the HybridDictionar y using the SyncRoot property.

Enumerating through a collection is intrinsically not a thread-safe
procedure. Even when a collection is synchronized, other threads could still
modify the collection, which causes the enumerator to throw an exception. To
guarantee thread safety during enumeration, you can either lock the
collection during the entire enumeration or catch the exceptions resulting
from changes made by other threads."

So if my singleton factory inherited from this HybridDictionar y and followed
the fourth pattern, am I good, since 1) the factory itself would be a
singleton and 2) the public static collection would is thread-safe? (The
above caveat about enumeration taken into account, of course)

Or are they just locking internally anyway when they say it is thread-safe?

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
Yeah but I would need the Factory to be a Singleton also or it defeats the purpose. So I need a GetFactory() and then a GetCustomer() I guess.


Well, the factory methods themselves needn't be part of an instance -
you don't need to have a separate class. Any reason not just to have a
static GetCustomer method?
As to the locking... help me sort this out in my head. The problem is two threads could call GetCustomer() right?


Yes.
Since that isn't addressed by the
Singleton nature of the factory itself the locks are required.


Yes.
So I could follow the 4th pattern for the factory itself and then use the locks within GetCustomer(). Right?


Yes, if you want to.
Not that the locking in the overall
pattern probably matters much at that point since I'm going to be locking left and right in the other method anyway.


Right.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #5
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
Yes I think I see your point. There's no need for there to ever be an
instance of the factory, as it's only purpose is to expose the static
GetCustomer() (in a Singleton way, of course).
Well, in a thread-safe way, effectively.
I think I understand that while I could be assured there is only one static
collection, multiple threads calling GetCustomer() could be adding, objects
to it, which would most likely result in a mess. In other words, it's the
fact that my main Singleton object is a collection type, which is by
definition continually changing, that's the problem.

But it appears maybe Microsoft is ahead of me. This is from the Thread
Safety section for HybridDictionar y:
"Public static (Shared in Visual Basic) members of this type are safe for
multithreaded operations. Instance members are not guaranteed to be
thread-safe.
That's not particularly unique to HybridDictionar y, of course. Most
classes in .NET are documented in that way...
So if my singleton factory inherited from this HybridDictionar y and followed
the fourth pattern, am I good, since 1) the factory itself would be a
singleton and 2) the public static collection would is thread-safe? (The
above caveat about enumeration taken into account, of course)

Or are they just locking internally anyway when they say it is thread-safe?


I'm afraid I've lost the plot slightly at this point - but I'm sure
you'll have to do *some* locking yourself to get the behaviour you
want. A simple implementation of:

static Hashtable customers = new Hashtable();

static object padlock = new object();

static Customer GetCustomer (string id)
{
lock (padlock)
{
if (!customers.Con tainsKey(id))
{
customers[id] = new Customer(id);
}
return (Customer) customers[id];
}
}

or something similar would be your best bet, I believe.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Sorry I lost you - it's my confusion rubbing off probably. :) I realize
that thread-safe claim would be true of most if not all of the collection
classes.

I don't think your example below assures there is only one collection, does
it? Or did you just intentionally leave out those details?

My thinking is that since MS says the collections are thread-safe I wouldn't
need to worry about the locking if GetCustomer(). In the case of the
Hashtable there's a synchronized wrapper, so this is what I'm thinking: (Of
course, if all the syncronized version is doing is using locks anyway than
it probably doesn't matter.)

public class CustomerCollect ion
{

static CustomerCollect ion customers = new CustomerCollect ion();
static CustomerCollect ion syncedCustomers =
Hashtable.Synch ronized(custome rs);

static CustomerCollect ion()
{
}

private CustomerCollect ion()
{
}

public static Customer GetCustomer(str ing id)
{
if (!syncedCustome rs.ContainsKey( id))
{
syncedCustomers[id] = new Customer(id);
}
return (Customer) syncedCustomers[id];
}

}
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
I'm afraid I've lost the plot slightly at this point - but I'm sure
you'll have to do *some* locking yourself to get the behaviour you
want. A simple implementation of:

static Hashtable customers = new Hashtable();

static object padlock = new object();

static Customer GetCustomer (string id)
{
lock (padlock)
{
if (!customers.Con tainsKey(id))
{
customers[id] = new Customer(id);
}
return (Customer) customers[id];
}
}

or something similar would be your best bet, I believe.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #7
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
Sorry I lost you - it's my confusion rubbing off probably. :) I realize
that thread-safe claim would be true of most if not all of the collection
classes.

I don't think your example below assures there is only one collection, does
it? Or did you just intentionally leave out those details?
It ensures there's only one collection per AppDomain, certainly -
because it's only created when the static initializer runs.
My thinking is that since MS says the collections are thread-safe I wouldn't
need to worry about the locking if GetCustomer().


No, because you need to go through the process of:

1) Test if the customer is already there
2) If it is, return it
3) If not, create a new customer and put it in the collection

Another thread could come in and request the same ID between steps 1
and 3, meaning you end up with two customers for the same ID. Only each
individual step is thread-safe without locking - you need to
effectively do the whole operation atomically.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
Well, of course. But for thread-safeness it's the 3rd step that is of
significance. That is to say, setting aside my specific application, the
problem is two threads attempting to add the same ID. I take "A Hashtable
can support one writer and multiple readers concurrently. To support
multiple writers, all operations must be done through this wrapper only." to
mean the synchronized Hashtable itself wouldn't allow that, and I'd end up
with an ArgumentExcepti on. How do you take it? (That's assuming I use the
Add method which maybe is not the code you posted before as I recall.)

Now, that's not to say that using locking isn't better than dealing with the
exceptions, if that's where you'll go next. I'll have to evaluate that. I
just want to make sure I'm understanding these concepts correctly first
though.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
My thinking is that since MS says the collections are thread-safe I wouldn't need to worry about the locking if GetCustomer().


No, because you need to go through the process of:

1) Test if the customer is already there
2) If it is, return it
3) If not, create a new customer and put it in the collection

Another thread could come in and request the same ID between steps 1
and 3, meaning you end up with two customers for the same ID. Only each
individual step is thread-safe without locking - you need to
effectively do the whole operation atomically.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #9
Daniel Billingsley <db**********@N O.durcon.SPAAMM .com> wrote:
Well, of course. But for thread-safeness it's the 3rd step that is of
significance. That is to say, setting aside my specific application, the
problem is two threads attempting to add the same ID. I take "A Hashtable
can support one writer and multiple readers concurrently. To support
multiple writers, all operations must be done through this wrapper only." to
mean the synchronized Hashtable itself wouldn't allow that, and I'd end up
with an ArgumentExcepti on. How do you take it? (That's assuming I use the
Add method which maybe is not the code you posted before as I recall.)
No, you wouldn't end up with an ArgumentExcepti on - you'd end up with
each call locking all other calls out until it completed.
Now, that's not to say that using locking isn't better than dealing with the
exceptions, if that's where you'll go next. I'll have to evaluate that. I
just want to make sure I'm understanding these concepts correctly first
though.


The problem is that if two different threads can both reach step 2, you
create more than one object for the same ID, which is usually a bad
move.

With threading, I always take the "simple is best" approach: while
you're dealing with shared data, take out a lock. I think people
generally believe that locks are more expensive than they really are.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

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

Similar topics

14
3217
by: lawrence | last post by:
To call I would do something like: $headline = McSelectJustOneField::callDatastore("cbHeadline"); Is this the correct use of the static keyword, to implement a Singleton design?
4
8237
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class? Let's start with your basic Singleton class: class Singleton {
13
8302
by: Stampede | last post by:
I woundered if the following would be possible: I want to create an abstract Singleton class, which implements the singleton behaviour with the limitation, that the unique object will not be created within the getInstance() method. The classes which are derived from the Singleton class, have to implement a static constructor, where they load an instance into the static unique variable. Now I have to problems with that:
21
2461
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
2
1308
by: Rick | last post by:
A coworker has brought up the following quote from a book as confirmation that we cannot use Singletons in ASP.Net application code, at least at the ASP.Net tier. I am looking for references to other documentation that confirms this quote or refutes it or expert comment on whether to use a Singleton in the ASP.Net web projects. The following quote is from the book Programming Distributed Applications with COM+ and Microsoft Visual...
4
3053
by: Simon Hazelton | last post by:
Is it possible in VB.net to have a single or singleton instance of a class per specific database record. I'm writing an auction site and have a problem with resolving proxy bids, effectively I am creating an unlimited amount of "Auctioneers" for the site as a whole (which is definitely wrong). I could create a singleton "Auctioneer" Class for the site with a singleton but feel this would be a performance botleneck. Ideally I would...
9
14140
by: Marcel Hug | last post by:
Hallo NG ! I Have a little question about inheritance of a singleton class. In my application i have a Database-Connection Lib, in which I would ¨like to connect different databases of the same project (thats why it is in a lib). For the database A I created a singleton class AProxy and for the database B the same as BProxy. Initializing and connetcing to the Database is the same in both classes (except of the database-path, which is a...
7
1427
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?
3
18246
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
0
8840
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
8730
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
9367
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
9064
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
6669
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
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3189
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
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.