aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Alternate to Singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Alternate to Singleton pattern" Watch "Alternate to Singleton pattern" New topic
Author

Alternate to Singleton pattern

Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello all,

Can anyone shed some light on how to create a Java file that is similar to the singleton pattern?

User should create only one instance of the "class"

Rgds,

Seetesh
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Please tell us more - what exactly is it that you want to do, and why? What alternatives did you already consider, and why didn't you use them?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello again,

I tried to use a file locking mechanism in order to get this functionality to check the instance of the class if it was running but then there were some cases where in a Windows XP Server, I had the GC problem and the file's lock got released.

Another example tried was listening to some Socket (Server and client programs) and using the exception thrown as a result of the Bind operation but then again the Firewall issue made me rethink of the same.

So any other option left other than making the class final and private but then how do I achieve the "single/one instance of the class" like the Singleton pattern.

Rgds,

Seetesh
anurag priya
Ranch Hand

Joined: Dec 19, 2000
Posts: 72
Hi Seetesh ,
Just make everything in the class as static (methods , attrubutes ), so it doesn't matter how many instances are created still all will be refereing to only one instance .
thats the simplest way of doing it .
regards .


Anurag priya
SCJP 2(83%); Brain Bench Certified for: Masters level EJB2.0(97%) - Masters level J2EE (83%) - BEA-WebLogic Application Server8.1 (86% )
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
Seetesh:
User should create only one instance of the "class"

If this is what you want, the Singleton pattern is the way to enforce that constraint. However, you should consider if there really is a strict requirement to enforce the constraint technically -- a "soft" guidance for developers to "just create one" is often a good enough solution, although it does run the risk of someone indeed creating two instances of the class.

Originally posted by anurag priya:
Just make everything in the class as static (methods , attrubutes ), so it doesn't matter how many instances are created still all will be refereing to only one instance .
thats the simplest way of doing it .

That may technically be the simplest way of doing it but it might not be the best way of doing it.

Using static methods significantly hinders testability and implementing a Singleton is a trivial task and not that much more lines of code compared to a class with all static methods:


Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Seetesh, am I understanding you correctly that you want to prevent more than one instance *even across several VMs*?

Could you please explain where your requirement is coming from, that is *why* you want to enforce that?
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Ilja,

=====================================================
Seetesh, am I understanding you correctly that you want to prevent more than one instance *even across several VMs*?

Could you please explain where your requirement is coming from, that is *why* you want to enforce that?
=======================================================

Currently my requirement is on a single VM.

My requirement is finding an alternate solution to the Singleton pattern so that I can implement the same for restricting any thin clients trying to access the object created so that only one client has access to the Class defined. (Something like implementing a SingleThreadModel concept)

Rgds,

Seetesh
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Anurag,

===================================================
Just make everything in the class as static (methods , attrubutes ), so it doesn't matter how many instances are created still all will be refereing to only one instance .
thats the simplest way of doing it .
===============================================

If I create a class and add static attributes/methods to it, the instance created for this class is still more than one. The client still creates multiple instances of the class and then accesses the static attributes/methods.

This attribute/method access comes after creating the instance of the class. I want to restrict this to one instance for one client. Getting my point/query.

Any inputs?

Rgds,

Seetesh
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello lasse,

=========================================
If this is what you want, the Singleton pattern is the way to enforce that constraint. However, you should consider if there really is a strict requirement to enforce the constraint technically -- a "soft" guidance for developers to "just create one" is often a good enough solution, although it does run the risk of someone indeed creating two instances of the class.
============================================

Is Singleton the only solution? No other way around to achive the same!!!

Rgds,

Seetesh
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Seetesh Hindlekar:
My requirement is finding an alternate solution to the Singleton pattern so that I can implement the same for restricting any thin clients trying to access the object created so that only one client has access to the Class defined. (Something like implementing a SingleThreadModel concept)


I'm sorry for being such a pain, but I think this is vital to know to help you effectively: why do you need this (something like a SingleThreadModel)?

BTW, in my current understanding, a Singleton wouldn't work for you - it wouldn't restrict access to one client at a time.
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
Originally posted by Seetesh Hindlekar:
=========================================
If this is what you want, the Singleton pattern is the way to enforce that constraint. However, you should consider if there really is a strict requirement to enforce the constraint technically -- a "soft" guidance for developers to "just create one" is often a good enough solution, although it does run the risk of someone indeed creating two instances of the class.
============================================

Is Singleton the only solution? No other way around to achive the same!

The Singleton pattern is a rather generic design pattern -- whatever you do in your code to enforce no more than a single instance (or some other, limited number of instances) to ever be created, your solution will be called a Singleton. The solution I posted earlier just happens to be one of the more common ways of implementing a Singleton.
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Lasse,

================================

The Singleton pattern is a rather generic design pattern -- whatever you do in your code to enforce no more than a single instance (or some other, limited number of instances) to ever be created, your solution will be called a Singleton. The solution I posted earlier just happens to be one of the more common ways of implementing a Singleton.

==========================================

Singleton pattern is normally applicable to a single client application trying to instantiate a Class ie trying to instantiate this class more than once in its execution path.

I am looking something like 'n' nos of clients trying to instantiate this class object. So only one client should be able to instantiate this class while others should get a message that the class is already instantiated by some other client.

Any inputs from ur side is highly appreciated.

Rgds,

Seetesh
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Ilja,

=======================================================

BTW, in my current understanding, a Singleton wouldn't work for you - it wouldn't restrict access to one client at a time.

=========================================================

Ur absolutely right. As you have mentioned, I know that Singleton is not appropriate for my application. I need to code much more beyond that but taking the Singleton pattern into consideration.

The application to be designed is supposed to take care of this multiple clients modifying the "source" and thats why we need to implement the instantiation of the class.

Also to add to this application, we are not using any web services or app servers. Its just a application to be developed and to be installed on our server allowing clients to invoke the same but at a time only one client will do the updation.

Rgds,

Seetesh

Rgds,

Seetesh
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
Originally posted by Seetesh Hindlekar:
Singleton pattern is normally applicable to a single client application trying to instantiate a Class ie trying to instantiate this class more than once in its execution path.

The GoF book defines Singleton as follows:
Ensure a class only has one instance, and provide a global point of access to it.

There's no mention of the number of clients of that Singleton class being limited to one. That's the whole point, really -- regardless of how many pieces of code are using the Singleton class, there only exists one instance of the Singleton class in that JVM.

Originally posted by Seetesh Hindlekar:
I am looking something like 'n' nos of clients trying to instantiate this class object. So only one client should be able to instantiate this class while others should get a message that the class is already instantiated by some other client.

So are you saying that an attempt to call "getInstance()" on the class should throw an exception if someone else has already called it?

By the way, what do you mean by "a client"? Are these "clients" in the same JVM as the class you want to restrict access to?
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336


I am looking something like 'n' nos of clients trying to instantiate this class object. So only one client should be able to instantiate this class while others should get a message that the class is already instantiated by some other client.

This sounds odd. Can you explain why you want to block other objects from instantiating an instance of one particular class if other objects have already instantiated the limit of permitted instances?

Controlling the number of instances a "singleton" can create is easy enough - just add a counter to it. Of course its no longer a singleton - but some sort of "multiton" (I just made that up - so don't go searching for a definition!).


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
If you're really looking for single threading, you might make all access to your single object through a synchronized static method. You could hide the single object completely behind the synchronized facade so clients never even know what it's called.

Another approach might be to put requests for the single object onto a queue and have it process the requests one at a time. That probably introduces asynchronous processing that might not work with a client's request-response expectations.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Seetesh Hindlekar:

The application to be designed is supposed to take care of this multiple clients modifying the "source" and thats why we need to implement the instantiation of the class.

Also to add to this application, we are not using any web services or app servers. Its just a application to be developed and to be installed on our server allowing clients to invoke the same but at a time only one client will do the updation.


Let me try to reformulate in my own words, to see wether I understand that correctly:

You have some centralized data. That data can get changed by a number of clients, through the use of a single class/object. To prevent conflicts, you only want one client at a time being able to change the data.

Did I get that right?
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Lasse,

=========================================
1. So are you saying that an attempt to call "getInstance()" on the class should throw an exception if someone else has already called it?

2. By the way, what do you mean by "a client"? Are these "clients" in the same JVM as the class you want to restrict access to?

================================================

1. Yes.
2. Currently I am catering to clients in the same JVM but later on it should support multiple JVM's too.
As I will be porting my application on a remote server for clients to invoke the same without having the need to install it on thier local machine. But this is a remote thought.

Rgds,

Seetesh
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Stan,

I will just try to fix the bug using ur advice. Will get back shortly.

Rgds,

Seetesh
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Ilja,

===============================================
You have some centralized data. That data can get changed by a number of clients, through the use of a single class/object. To prevent conflicts, you only want one client at a time being able to change the data.
==================================================

Yes.

Currently the "centralized data" is a Object but later on it could be some data stored in xml or any other file as per the requirement.

Rgds,

Seetesh
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
For multiple JVMs you're going to have to find some kind of external lock.

Database transactions are awfully good at these concurrency problems. Writing a lock record, doing the access, removing the lock record might seem like a lot of overhead, but I'm not sure anything else would be faster.

Or we could get real ... Make a special lock mgr JVM - maybe just one out of the cluster. Any jvm that wants access sends a request to the lock mgr and eventually gets a token back that allows access. When done with the shared resource, return the token to the manager so it can pass the token to the next requestor in line. Choose any protocol you like for inter-JVM communication ... sockets, JMS, EJB, etc. You might want load balancing and fail-over for your lock mgr. Yikes, this could get out of hand!
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Stan James:
For multiple JVMs you're going to have to find some kind of external lock.


The way I understood the description, the clients could live in different VMs, but they would all access a single shared resources living in a single VM?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Could be. Let's go to the judges ... Seetesh?

A shared resource per VM would be no problem. A shared resource among many VMs is more work.
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Stan/Ilja,

The client can be in any JVM. My program should be least concerned of the client accessing/instantiating this class file.

As mentioned in my earlier post

"I tried to use a file locking mechanism in order to get this functionality to check the instance of the class if it was running but then there were some cases where in a Windows XP Server, I had the GC problem and the file's lock got released."

How do I keep my lock secured ie not get that released ie prevent GC?

Rgds,

Seetesh
Jeremy Thomerson
Greenhorn

Joined: Feb 17, 2005
Posts: 3
I'm definitely not sure that I understand the question your asking or the use-case that you are describing. However, you are indicating that you want the call to "getInstance()" or similar to throw an exception if that instance is in use. If this is correct, would it be feasible to simply create an object pool that contains only one object? The commons project allow easy object pool creation / use. Then you could say "borrowObject()", get the object, use it, and then "returnObject(obj)" when you are done. Any calls to "borrowObject()" while the one instance in the pool is being used would result in an exception.

Not sure if this helps at all, but hopefully it will. Also, those may not be the exact method names, but they illustrate the point.
[ February 17, 2005: Message edited by: Jeremy Thomerson ]

Jeremy Thomerson<br />Software Engineer, eBay, Inc.
Seetesh Hindlekar
Ranch Hand

Joined: Feb 13, 2004
Posts: 244
Hello Jeremy,

The Singleton pattern now evolves abt the Object pool now and not on the main control of creating the instance of the class required and its access by "clients".

Else U mean to say that Object pool is handled in the code while declaring the class.

Rgds,

Seetesh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Alternate to Singleton pattern