Re: Singleton Pattern
At PerSe Technologies, we have implemented the singleton pattern in our
Enterprise Component Toolkit Framework. We have what we call our "shared
data managers", which are visible to the appropriate architecture layer.
We did not implement this as a service object and do not use a Forte
"Shared" object. Instead, we use mutexes to control data locking ourselves
which allows multiple tasks to execute against the shared data manager
concurrently. This approach ensures us that we have one and only one copy
of a given object at a time. Our approach also gives another benefit in
that it caches frequently accessed data and has improved overall
performance of our applications.
Dustin Breese
[email protected]
Supervising Technical Consultant
PerSe Technologies
From: Mark Addesso <[email protected]>
Date: Mon, 2 Feb 1998 12:36:02 -0500
Subject: Implementing the Singleton pattern
Has anyone implemented the singleton pattern in Forte? A singleton is =
simply ensuring that there is one unique instance of a class. In other =
OO languages I would create a class method which would use a class =
variable to hold onto the unique instance. Since forte doesn't have =
either of these (class methods or variables), I'm not sure how to do it.=
I thought of using named objects, but it seems like a heavy =
implementation. Any ideas.
Is the danger that someone might make the Singleton
cloneable really a the most important reason to make a
Singleton non-extensible? I think not.It IS a good reason if cloning or subclassing it means
you can end up with more than one in the same JVM. If
you really implemented Singleton because "There Can
Only BE One", I'd say prohibiting subclassing and
cloning might be important.
I gotta go with the OP on this. That comment is abit queer.
I gotta go with the definition of Singleton on this
and disagree. It's not like it's that difficult.
Don't implement Cloneable or Serializable and make
the constructors private. Done. What's the
problem?
At some point it is just too much.
Are you going to implement a security manager as well? Because unless you do I can create JNI method and create a new object as well.
If they don't understand that the singleton is a singleton then are you going to assume that that is the only problem that they are having?
When I program I make assumptions about those that I work with and those that will come after me. I like to think that they have a minimal level of intelligent. They might not write the best code all the time but they do understand most of the ideas. And given that singleton the most used and probably easiest pattern to understand is it really necessary to be so protective?
Similar Messages
-
How can we send only one message to a WCF service at a time? How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file? Can we do it by Host throttling?
Hi Pawan,
You need to use WCF-Custom adapter and add the ServiceThrottlingBehavior service behavior to a WCF-Custom Locations.
ServiceThrottlingBehavior.MaxConcurrentCalls - Gets or sets a value that specifies the maximum number of messages actively processing across a ServiceHost. The MaxConcurrentCalls property specifies the maximum number of messages actively
processing across a ServiceHost object. Each channel can have one pending message that does not count against the value of MaxConcurrentCalls until WCF begins to process it.
Follow MSDN-
http://msdn.microsoft.com/en-us/library/ee377035%28BTS.10%29.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx
I hope this helps.
Rachit
If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply. -
Use of Singleton pattern in Distributed environment
Can somebody say why it is not advisable to use Singleton pattern for developing client server applications.
Client-server does not imply distributed environment, IMHO. There are pretty simple C/S architectures where Singleton pattern is not generally a bad thing.
Distributed environments usually have multiple VMs running, while the singleton pattern typically implemented is a per-VM singleton. -
Serializing a class that implements the Singleton pattern
Hello,
I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
I have a class that implements the singleton pattern. It's definition is as follows:
public class JCOption implements Serializable {
private int x = 1;
private static JCOption option = new JCOption();
private JCOption() {}
public static JCOption getOption() { return option; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public static void main(String args[]) throws IOException {
JCOption opt = JCOption.getOption();
opt.setX(10);
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
encoder.setPersistenceDelegate(opt.getClass(), new JCOptionPersistenceDelegate());
encoder.writeObject(opt);
encoder.close();
}Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
protected Expression instantiate(Object oldInstance, Encoder out) {
Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
return expression;
}The problem is that the resulting XML file only contains the following lines:
<java version="1.5.0_06" class="java.beans.XMLDecoder">
<object class="JCOption" property="option"/>
</java> so there is no trace of the property x.
Thank you in advance for your answers.How about this:
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.Expression;
import java.beans.Statement;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class JCOption {
private int x = 1;
private static JCOption option = new JCOption();
private JCOption() {}
public static JCOption getOption() { return option; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public static void main(String args[]) throws IOException {
JCOption opt = JCOption.getOption();
opt.setX(10);
ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder( os );
encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
encoder.writeObject(opt);
encoder.close();
System.out.println( os.toString() );
class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
protected Expression instantiate(Object oldInstance, Encoder out) {
return new Expression(
oldInstance,
oldInstance.getClass(),
"getOption",
new Object[]{} );
protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
super.initialize( type, oldInstance, newInstance, out );
JCOption q = (JCOption)oldInstance;
out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
} Output:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_06" class="java.beans.XMLDecoder">
<object class="JCOption" property="option">
<void property="x">
<int>10</int>
</void>
</object>
</java> -
Best Practice: Using a static variables and methods vs singleton pattern
Just curious, since when anything, within a class, is denoted as static it typically will be stored in main memory as a class property(method, variables, etc). Is it a good practice to be doing this all the time or is the singleton pattern a better choice. Please explain why. Thanks.
I wouldnot make anything other than the constants and the instance itself static. And I cant think of a reason wjy one would.
-
Is abap thread safe? Some question in Singleton pattern in ABAP
Hi Grus,
I have a very basic question but really make me headache...
Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
Could you help me on the question? Thanks a lot, grus
And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
BR,
SteveSteve,
I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
Best regards. -
Implementing Singleton Pattern in ESB
How do I go about implementing a singleton pattern within the ESB. Example usage would be for a cache. Prior to making an expensive service call I want to make sure that the data does not already exist within the cache.
Have a look at metalink note 746108.1
cheers
James -
Per Web Application singleton pattern
Hello
I have a application (ear) file that look something like this:
App.ear
-- Web_1.war
----- WEB-INF/lib/helper.jar
-- Web_2.war
----- WEB-INF/lib/helper.jar
-- Web_3.war
----- WEB-INF/lib/helper.jar
inside helper.jar there is a singleton class., which get initialised differently depending on which Web_<X> it is loaded in. This currently works because each lib directory get loaded by each own classloader.
I would really like to move the helper.jar up to the <ear file>/lib directory, but that means it is only loaded by the classloaders once anf thus the 3 singletons break as there is now only one.
I would like to have some sort of "Per Web application" globally reachable "singleton".
I have thought about using ServletContext, but it appears that there is no easy ways for helper classes to look it up, unless it is passed as a parameter.
A second idea would be to use ThreadLocals, but that would rely on the Web container not reusing threads accross web applications. I am not sure if this is guranteed not to happen ...
In any case, what is the best way to handle this ? is there any standard way or a design pattern to follow...I suppose another way of asking this question is this:
is there a way to use the singleton pattern on a
per-web-application basis without storing the
singleton in the ServletContext? If I can find a way
to do that, I can solve my initial problem.Some web application servers run each webapp in a separate JVM, or at least a separate classloader. If yours does either of those, then each webapp will have its own instance of the singleton. Try it. -
if i use Class.forName(MyClass).newInstance() to init MyClass and MyClass uses singleton pattern, i wonder what is the difference between Class.forName(MyClass).newInstance() and Class.forName(MyClass).newInstance().getInstance(),i meant whether the former object is singleton or not(plz tell me why). or i should never let sth like this happen(i should not use both Class and singleton,plz tell me the reason 2) or is there any other pattern than can combine both of them.
any discussion will be appreciated.thanx in advance
Ciao,
zhxthi scratchback,
are you sure that MyClass uses singleton pattern? I haven't tried Class.forName(MyClass).newInstance() in a singleton class before, but I don't think it will work if your constructor is private.
singleton pattern is used for classes that you think should exist in the application only once.
hope it helps..
ronron -
Sort of singleton pattern , design question
Hi
i need to a class which has only one instance( can use a singleton pattern) but the problem is there have to be some variables to be initialised and this class will not know how to initialise them, how do i desin it
public class MyData
private String data;
private String data2;
private static MyData instance;
public MyData getInstance()
return instance;
public String doSomeThing(String parm3)
// but parm1 and parm2 are not initalised, they are common for all classes,
// how do i desing it
return parm1 + parm2 + parm3;
ashishhi
I know it is not a good desing , but my problem is
that my SingleTon pattern is sort of worker class,
which will be accessed from many other classes, these
classes also dont know the values of parm1 and parm2
required by the worker class,
these values are setup by the startup java class
which reads them from a properties file, this worker
class has no knowledge of this properties file and
hence cannot retrieve it...
so what are my optionsHave the singleton get the values itself from system properties, or a file or database or java.util.Preferences or some other appwide configuration.
Or do what DrC suggested and have a factory do that and let the factory push the values to the singleton.
, i dont want to make these
variables static since there will be problem in my
applicationAnd what problem would that be? -
Candidates for use of Singleton Pattern
Hi
Can any guide me , where to use Single Design pattern in Java Based Applications
Should i use Singleton Pattern in the following situations
1)RMI Server
2)Controller Classes ( MVC) invoked by Servlet
3)Database cashing /handling classes
Please suggest other suitable places also
Thanks in AdvanceHii
Typical uses of a singleton pattern are in those cases where you have to have a single instance of a class.For example if u have an RMI based application and the client needs to perform a RMI lookup(for the URL etc)in that case for a particular user you wud like to have just a single instance for the lookup.
In case of controller classes invoked by the servlet you would typically not want a Singleton as multiple instances of the servlet might require to use a controller object.As the request parameters would be different for each servlet instance,you would need a controller object for each of them. -
Serializing object of class implementing Singleton Pattern
hi ,
if i've a object of a singleton pattern based class and i seriailize that and when i'm desrializing that, i 'll get the object back, but on calling getInstance() method for my singleton class, it will agian call constructor because for the class's static object reference is null, i need to avoid this, for this i've written a setInstance method, which sets the Singleton class's static refernce to the object i desialized, which is fine, but it defeats the singleton pattern
can anybody suggest me some other way of achieving this...If you are trying to deserialize a Singleton implement the Object readResolve() method.
http://java.sun.com/javase/6/docs/platform/serialization/spec/input.html#5903
~Ryan -
May I make a singleton pattern like this
as well know, singleton pattern in java always like the codes below:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
return instance;
but, when I read the java non-static initialization block section, I had an new idea about a this pattern. how about like this:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
static{
instance = new ClassicSingleton();
public static ClassicSingleton getInstance() {
return instance;
or like this
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
instance = new ClassicSingleton();
public static ClassicSingleton getInstance() {
return instance;
could anybody here tell me what's the different? thanks.I usually do something like this:
public class ClassicSingleton {
private static ClassicSingleton instance = new ClassicSingleton();
private ClassicSingleton() {
try{
/* Construction logic here. */
}catch(Exception e){
/* Something bad happened, decide what to do, like set a flag indicating singleton isn't valid. */
public static ClassicSingleton getInstance() {
return instance;
} -
Advantage of Singletone Pattern
What is Advantage of Singletone Pattern...????
Do some research
(Hint: Click the above link)
And it would be really swell if you'd learn to do this research yourself, as you've been prodded to do in some of your other threads. -
Describe a class in the JDK that uses the Singleton design pattern
I am sorry............... could you please explain a
class in JDK which follews singleton pattern?
I was asked this question in an interview yesterday?See reply #2 for a fine example of a potential Singleton object.
kind regards,
Jos
Maybe you are looking for
-
Downloaded 5.1.1 to my iphone. Now, Safari will not connect to my server. Can not download web pages and many of my apps. Email seems to be ok. iphone running slow and sluggish. I have read several other users have experienced the same problem. Any
-
A syntaxic question...
Hi guys, I've posted about this on this very forum before, but I can't find my own question... and the answers that you people provided, so I'll do it again: what's wrong with the following, knowing that I have Developer Tools installed and that I cl
-
I have configured a Jco in my SLD, configured a system in the portal and the connection test to the backend is successful. I then changed the System properties in the portal to SNC and the connection still worked. I then changed the JCo in the SLD bu
-
Why is my tool bar pixelated? software-10.6.8
Why is my tool bar pixelated? software-10.6.8 Well, my upper screen tool bar keeps going a blueish white pixelation. I can stop the the problem for a bit by changing the back screen display or by shutting the whole system down and then back on.
-
Send IDOC from Business Connector to SAP faster
Hi Developer! I need to send a very lot of IDOC converted from XML files from the Business Connector to SAP. The XML files are in different directories pro business partner, but they have a same type (ISU_MSCONS). My problem, that the import take a l