• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Alternate to Singleton pattern

 
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Seetesh Hindlekar
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 .
 
author
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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:
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?
 
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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!).
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Stan,

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

Rgds,

Seetesh
 
Seetesh Hindlekar
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Seetesh Hindlekar
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic