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 Advance

Hii
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.

Similar Messages

  • 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?

    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.

  • Singleton pattern over Factory pattern

    What is the difference between the Factory and Singleton pattern.
    Can we use a singleton (pattern) class to create other object instances and return them.
    What are the advantages and disadvantages for using the Singleton pattern here.
    Or do we have to use only a factory (pattern) class to do the above type of task.

    The Factory pattern and the Singleton pattern are used to achieve different things. That's not to say they can't be used together. A Singleton pattern is used to force the use of a single instance of a class, hence the name. The Factory pattern is used to determine at runtime what class will be used.

  • Candidates for HANA sidecar usage

    Hello folks - we have a financial landscape running ERP6 EHP4 on Oracle RDBMS, and are considering 2 options
    1) once ECC/ERP on HANA is available - migrate to HANA from Oracle (so the entire system would run on HANA)
    2) setup a sidecar HANA - and then use it for a select group of tables/processes - to help improve performance against those objects (so data from the ERP system would get pulled into the HANA sidecar and queries/jobs would run against the sidecar instead of the original ERP system itself)
    For the 2nd option - is there any SAP service or tool that can help us pinpoint what tables would be the best candidates for use in the sidecar?  I can't find this anywhere but would think SAP would be more than happy to guide customers to anything that gets them using HANA. (the first option is probably more long-term for us BTW)
    Thanks

    Hi Ben,
    As you have mentioned, Option 1 should always be the long term approach. However , to leverage the benefits of HANA immediately, suggested approach could be to choose option 2, i.e. HANA is used in side car approach, where in the SAP products - ERP, CRM, SCM etc continue to use classical database , but the table and data in these are replicated to HANA database. This can be done for selected scenarios or select transactions / business processes - ex: - CO-PA or Custom transactions / reports that have huge performance issues.
    Following SAP tools can be used to identify potential programs/scenarios for Optimization.
    SQLM- SQL Monitor - This logs all the SQL statements that are executed on an ABAP application , would help to identify the programs that have performance issues due to SQL statements. The log for around 1-2 weeks can be checked to identify potential areas of optimization.
    SWLT- Performance Tuning Worklist    - Used to combine static check results with SQLM snapshot to identify the hotspots  within programs. We can use this tool in the production system for few days to identify the programs/transactions that need optimization.
    Enhanced SCI- Code Inspector  - this tool can be used to perform Static checks within ABAP programs and identify code patterns that could be optimized. This can be very useful for Custom ABAP programs and can be readily used in dev/quality systems as well.
    SAP also suggests the use of  Business scenario recommendations report for SAP Business Suite powered by SAP HANA, This report identifies the specific business value scenarios most relevant to you after analyzing your current production usage and your productive SAP landscape. Although this is suggested for option 1, same can be used to identify potential areas of Optimization. Details of the same can be found on www.suiteonhana.com , you will need to upload your production log details so that you can receive your results report by email. The site also has a sample report.
    Regards,
    Suma

  • 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.

  • 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;
    ashish

    hi
    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?

  • 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,
    Steve

    Steve,
    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.

  • How to split a string for 2 different matching patterns?

    hey guys
    i'm trying to split a string, using .split(regular expression), if two different pattern matches but i don't know the exact syntax for it. I want to split the string from letters and punctuations.
    This is what i'm doing, obviously it's not working, i'm not too sure if syntax are correct.
    String inputDigit [] = input.split("([a-zA-Z]) (\\p{Punct})");Please help me with this, thank you!

    Can you describe in more detail what you're trying to
    accomplish?ok, basically if you have a string which consists of letters, digits and punctuations. All i'm trying to do or want to do is store all digist within that string into an array. Therefore, i'm using split method to split the string wherever you find a letter or a punctuation. But i don't know what is syntax for using two different patterns at the same time.
    // For example if you have a string "Eeyore 61 2.986PoohPiglet007Kanga-23"
    // i only want: 61 2 986 007 23. I know i can use substring // but that would be a slightly long process

  • Alternative Singleton pattern

    I'm sure someone must have thoguht of this before - but it struck me when I was using the Singleton pattern today.
    Obvisouly we know that the getInstance() method must be synchronized to prevent "mutliple singletons" being created, and the whole Double checked locking issues that arise from tryig to get around this.
    So, how about the following (non synchronized) version?
    class Singleton{
        private static Singleton staticInstance = new Singleton();
        private Singleton(){
            //private constructor
        public static Singleton getInstance(){
            return staticInstance;
    }Ok, so the instance isn't created "on demand", but lets face it all singletons are accessed at some point, so why not just create it when the class is loaded? Surely this will garuntee that only one copy is ever created or am I missing something obvious?

    It isn't obvious
    to me why the class would be loaded before the first
    reference to it, but perhaps there are some nuances
    (such as the EJB example) that I am not seeing.The difference is very nuanced. Actually I'm glad you posted this because I had the mistaken belief that the static initialization occured before the code started executing. However, there is still a difference.
    The static version gets loaded when the class is loaded. The lazy version gets executed when the getInstance method is executed. I had to contrive an example to show this, but I'm pretty sure that it does come up in certain environments.
    public class Garbage
        static String value = new String("Garbage");
        public static void main(String[] args)
            StaticSingleton.nothing();
            LazySingleton.nothing();
    class StaticSingleton
        private static StaticSingleton instance;
        static
            instance = new StaticSingleton();
        private StaticSingleton(){
            System.out.println("Constructing StaticSingleton");
        public static StaticSingleton getInstance(){
            return instance;
        public static void nothing()
    class LazySingleton
        private static LazySingleton instance;
        private LazySingleton(){
            System.out.println("Constructing LazySingleton");
        public synchronized static LazySingleton getInstance(){
            if (instance == null)
                instance = new LazySingleton();
            return instance;
        public static void nothing()
    }

  • Example for singleton pattern

    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

  • Do I need a Singleton pattern for this case

    Hello,
    I'm writing a game in Java and I have a very simple score manager class which just tracks the points the player so far has. I need to access this class in different pars of my app (gui, game core ...) so I created a singleton class which looks like this
    public class ScoreManager {
            private static ScoreManager instance = new ScoreManager();
            private int score = 0;
         private int highScore = 0;
         public static ScoreManager getInstance() {
              return instance;
         public int getScore() {
              return score;
         public int getHighScore() {
              return highScore;
         public void addScore(int scoreToAdd){
              score += scoreToAdd;
              if(score > highScore) {
                   highScore = score;
    }so far so good ..
    I would like to read the "highScore" from a file when the game starts and write it back when the game ends. I added those two methods:
         public void init(File highScoreFile) {
              highScore = readFromFile(highScoreFile);
                    score = 0;               
         public void dispose(File highScoreFile) {
                   writeToFile(highScoreFile);
         }So basically I call the init() method when the game stars and the dispose() when the game ends.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place.
    What would be a better way to do this ?
    Thanks for your help,
    Jesse

    safarmer wrote:
    You could keep track of the state (initialised, destroyed etc) in the manager and only perform the action if it is an expected state.
    private enum State { NOT_INITIALISED, INITIALISED, DESTROYED};
    private State currentState = State.NOT_INITIALISED;
    // i will leave the rest up to your imagination :) this looks good, thanks
    anotherAikman wrote:
    >
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. And who would that be? You´re the only one using the code, aren´t you?
    If not, you could still include in the documentation where to call those methods.
    no I'm not the only one working on this. Documentation can be useful but does not prevent calling wrong methods.
    YoungWinston wrote:
    I don't see any constructor. Usually, a singleton class should have a private one, even if it has no parameters. If you don't have any, Java will create a public no-parameter one as default.ok I forgot the private constructor.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. Then my advice would be not to make them public. After all, your code is the only one calling these methods - yes?yes only the code of the app calls it.
    If you are convinced that your game requires one and only one score manager, then a singleton is probably the best way to go.
    I'm a little worried about the init() and dispose() methods though, because these suggest state changes, which is unusual for the singleton pattern. You may want to think about synchronizing them.
    An alternative might be to use properties to get and store your scores.ok for the synchronization. What would using the properties ? It would be just another type of storage backend and I'd still need to read/write it.
    Thanks for your help,
    J

  • The error message "No more virtual tiles can be allocated" appears when I try to use the effects in the quick editing mode in my Elements 13. The baton OK has to be pressed several times for loading all effect patterns. The error returns when selecting th

    The error message "No more virtual tiles can be allocated" appears when I try to use the effects in the quick editing mode in my Elements 13. The baton OK has to be pressed several times for loading all effect patterns. The error returns when selecting the particular pattern.
    The problem does not appear, if PH Elements 13 is executed in the administrator mode.
    The available computer resources are rather  large enough: CPU INTEL i7 4 cores,  16GB RAM, 1TB HDD + 32GB SSD, Windows 8.1.
    Please, advice how to solve this problem? Maybe, there is patch or updating available?

    Dear n_pane,
    Thank you for the quick answer. In the meantime I found other way to pass by the problem. I increased the cache level up to the maximum value 8.
    The errors reported as "No more virtual tiles can be allocated" vanish, but I still do not understand, why PSE 13 cannot work properly by the lower cache levels, having available maximum resources it needed (10443 MB RAM and 26.53GB SSD space for scratches), or cannot collaborate with the fast SSDs properly.
    I wish you all the best in the New Year 2015!

  • Why the singleton pattern used rather than static things?

    class Single
        private Single() {}
        private void print() { System.out.println("Foo~"); }
        private static Single one = new Single();
        public static void print() { one.print(); }
    class Stat
        public static void print() { System.out.println("Foo~"); }
    }What's the different?? What is the benefit of the singleton one?

    There is no practical difference - because, in fact, that is not the singleton pattern!
    A singleton would look like:
    class Singleton {
        private Singleton() {}
        public void print() { System.out.println("Foo~"); }
        private static Singleton instance = new Singleton();
        public static Singleton getInstance() { return instance; }
    }The benefit of this pattern is, that your client code doesn't have to know that there is only one instance (getInstance could return another instance for every call) or of which actual type it is (getInstance could return an instance of any Subclass of Singleton).
    See http://c2.com/cgi/wiki?SingletonPattern for more information on the pattern.

  • 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.

Maybe you are looking for

  • Caps keyboard doesn't work. What am I missing?

    Hi folks. I'm currently making my way through the "starting with logic" manual, and am at the point where it describes how to record a track (page 48ish). I don't have a midi keyboard so want to use the caps keyboard, but it doesn't appear to be doin

  • IDVD menu troubles

    In iDVD when I preview my video the menu works fine, but when I play it in my DVD player on the tv it skips the menu completely and goes straight to the slideshow. How do I fix this?

  • Can you use facetime to call international cell phones

    Hi there- If I use Facetime to call an international cell phone (which is an iphone), will I be charged anything? I'll be calling over wi-fi on my end. TIA

  • Billing problem; now can't open

    There was a problem with my credit card, and for about a week, my Creative Cloud subscription was suspended. I updated the card information today, but for the past hour or so, I have been unable to use my Adobe products. Has anyone encountered this p

  • Importing MS Word into Flash

    I`m interpreting a large piece of MS Word text into movie shorts I mean to organize into an interactive `newspaper` style presentation that can be perused online. With `web-presentation`, I`m a true novice; so my first crucial question is: How, or ca