A question about singleton pattern

Will a singleton instance be a bottleneck of an application when many client address this instacne?
and How can I do to deal with this problem?
help me!

Unless the singleton has synchronized methods or blocks of code that are synchronized there should be no bottle neck, as multi threads can access it at the same time.

Similar Messages

  • Question about singleton design

    Hi all
    i have a question about singleton design. as i understood it correctly, this pattern garantees us a single instance of a class at any time. in a environment of concurrent access(multiple user access at the same time) , does this single instance put a constraint on concurrency(singleton == synchronization)? i have developed a service object that reads in properties and constructs some other objects. the reason i made it singleton is that i only want this service object to load the properties once. and when it is called to create other objects, it always has one copy of the propertis. making this service singleton, will it limit the threads to access it and construct other objects? thanks for your help.

    If there's no write access to the HashMap, then
    you're thread safe.You were probably typing at the same time as the previous post, which explicitly says there IS write access to the HashMap.
    I don't know what it is, but people seem to have this magical view of concepts. Singleton is just what it is. It doesn't have a magical aura that causes other things to behave differently. A singleton is just Java code that can have thread safety problems just like any other Java code. So to the OP: forget about the fact that this is a singleton. That's irrelevant. Ask if a method needs to be synchronized.
    (And yes, a method that tests if a variable is null and assigns an object to it if it isn't null does need to be synchronized if it's going to have multiple threads accessing it.)

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

  • About singleton pattern

    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,
    zhxt

    hi 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

  • Questions about DAO pattern

    Hi,
    I am a junior programmer and I am trying to understand somewhat more about best practices and design patterns.
    I am looking for more information regarding the DAO pattern, not the easy examples you find everywhere on the internet, but actual implementations of real world examples.
    Questions:
    1) Does a DAO always map with a single table in the database?
    2) Does a DAO contain any validation logic or is all validation logic contained in the Business Object?
    3) In a database I have 2 tables: Person and Address. As far as I understand the DAO pattern, I now create a PersonDAO and an AddressDAO who will perform the CRUD operations for the Person and Address objects. PersonDAO only has access to the Person table and AddressDAO only has access to the Address table. This seems correct to me, but what if I must be able to look up all persons who live in the same city? What if I also want to look up persons via their telephone numbers? I could add a findPersonByCity and findPersonByTelephoneNumber method to the PersonDAO, but that would result in the PersonDAO also accessing the Address table in the database (even though there already is an AddressDAO). Is that permitted? And why?
    I hope someone can help me out.
    Thanks for your time!
    Jeroen

    That is exactly what I am trying to do. I am writing it all myself to get a better understanding of it.
    Please bear with me, because there are some things I dont understand in your previous answer.
    1) Each BO validates his corresponding DTO and exposes operations to persist that DTO. Each DTO will be persisted in the database via his corresponding DAO. So this would be:
    - in PersonBO
    public void save(PersonDTO personDTO) {
    this.validate(personDTO); // does not validate the nested address DTOs
    this.personDAO.save(personDTO); // does not save the nested address DTOs
    - in AddressBO
    public void save(AddressDTO addressDTO) {
    this.validate(addressDTO);
    this.addressDAO.save(addressDTO);
    Am I viewing it from the right side now?
    2) Imagine a form designed to insert a new person in the database, it contains all fields for the Person DTO and 2 Address DTOs.
    How would I do this using my Business Objects?
    This is how I see it:
    // fill the DTOs
    daoManager.beginTransaction();
    try {
    personBO.setDao(daoManager.getDao(PersonDAO.class));
    personBO.save(personDTO); // save 1
    addressBO.setDao(daoManager.getDao(AddressDAO.class));
    addressBO.save(personDTO.getAddress(1)); // save 2
    addressBO.save(personDTO.getAddress(2)); // save 3
    daoManager.commit();
    catch(Exception e) {
    daoManager.rollBack();
    If I insert the transaction management inside the DAOs, I can never rollback save 1 when save 2 or save 3 fail.
    It can be that I am viewing it all wrong, please correct me if that is the case.
    Thanks!
    Jeroen

  • Question about bridge pattern

    its definition is "decouple an abstraction from its implementation so that the two can vary independently". I don't understand what "abstraction and the implementation vary independently" really mean and how .
    Before another question pls see the below class diagram of bridge pattern:
    http://images.cnblogs.com/cnblogs_com/zhenyulu/Pic91.gif
    My question is whether not using abstraction and just keeping implementation hierarchy can do the same thing? Interface and its implementation itself(polymorphism) can make extending easily and be well subject to open-closed principle,can't they?
    Sorry for my bad English.
    Edited by: fxbird on 2011-7-17 上午5:13

    fxbird wrote:
    jschell wrote:
    fxbird wrote:
    I think it's very common in j2ee development. Certainly isn't if someone is using a container.
    If someone is creating a container then I would suspect that such a pattern might be useful.
    However if someone is creating a container then there are going to be a lot of useful patterns. And lot of classes as well.
    And in total of the entire scope of creating a container the bridge would be a very small part.
    So it certainly isn't going to be "common".Hello jschell , what do you mean by 'container'? You phrased your comment about J2EE. A common idiom is to refer to a J2EE (actually newer name is JEE) server as a JEE container. Not sure why specifically that word is used but maybe because such servers are said to 'contain' applications.
    In my previous reply, the architecture I mentioned is ss(spring+struts2.x),the pattern I mentioned is a standard way. You either do not understand what I said or you do not understand what happens in those implementations.
    If I have 100,000 classes and 3 of them are implementing the bridge pattern then it is not "common".
    If I have 100,000 classes and 3,000 of them implement many bridge patterns (and not generated) then one could say it is "common".
    And having done some JEE applications I seriously doubt there is an implicit need to use the bridge pattern.
    The bridge pattern is intended to deal with a complex situation. Since there are more simple JEE applications than complex ones then it seems unlikely that there is a "common" need for it in JEE applications.
    Actual I've not been understood why it's used this way---define business interface, from my perspective, it doesn't have to define it, simply writing a business class and calling dao method is enough. I assume bo interface thing is a bridge pattern.I don't know why they would use the bridge pattern nor even if they really do. I wouldn't be surprised that it is used and I can also suppose that the use would be a good idea. Although it is quite possible as well that it is used incorrectly in some places.

  • Question about design pattern - business delegate

    hi guys
    i have got a question to ask about the delegate pattern. usually, we use it to decouple between presentation client and businessservice tiers. for instance, the service tier has an session ejb, and delegate wrapps the ejb. and the web client calls delegate to access service. is the delegate only used by the presentation tier? within the service tier, we can have many ejbs that work together to get tasks done. do we still use delegates in the service tier? what is ur suggestion? thanks

    Try the Patterns and OO Design forum.

  • Question about design pattern - business delegate: repost

    hi guys
    i have got a question to ask about the delegate pattern. usually, we use it to decouple between presentation client and businessservice tiers. for instance, the service tier has an session ejb, and delegate wrapps the ejb. and the web client calls delegate to access service. is the delegate only used by the presentation tier? within the service tier, we can have many ejbs that work together to get tasks done. do we still use delegates in the service tier? what is ur suggestion? thanks

    thanks, but i don't think i follow what u said.
    bascially i was asking if it was still a good idea to use delegates to communicate between ejbs the same way presentation tier calls service tier. i.e. SessionEJBA calls DelegateB to access SessionEJBB. or SessionEJBA calls SessionEJBB directly including the lookup, etc.

  • Question about commond pattern

    Hi!
    can somebody tell me about any good resource where i can get knowledge of designing controller on basis of command pattern and an example will help me a lot....
    I want to develop a controller for my application which except's data from swing client and calls the appropriate business components (session beans) to perform the requested task , asked by customer.....
    Also i need to design Factories for my objects and need good resource to get started from....
    thanx in advance
    sajjad ahmed paracha

    Also take a look at Struts on apache.org. You can either use Struts directly or, if you want to develop your own, look at how they architected things as a starting point.
    - Saish

  • Copyright Question about Adobe Patterns

    I have created illustrations for a book and am using Adobe Photoshop Elements to "color in" my drawings. In addition to the patterns which came with my program, I have downloaded patterns from Adobe Exchange. How would you suggest I reference/give credit to Adobe in my publication since these patterns are under copyright protection?

    Unless you sell it as your own creation (that is the pattern template/ swatches, not the result), the usage of provided content is covered in the EULA. No need to make any extra mention of specific stuff beyond perhaps a generic © Adobe for the relevant parts. For third-party content that may be different, but you should find the relevant info from the authors there...
    Mylenium

  • Question about DAO pattern

    Greetings.
    If I'm using EJB's in my application when does DAO fits in?? I mean, it is DAO an alternative to EJB's or a complement ??
    Thanks in advance.

    DAO fits in if you are using entity beans using bean managed persistence. In this case, the DAO brokers the database calls during the EJB's lifecycle. The other instance when you would use DAO would be if you forgo entity beans altogether. In this model, stateful or stateless session beans would use DAO's to broker the database calls directly, outside of the normal entity bean lifecycle. The DAO pattern can also be used with POJO's (plain 'ole Java objects).
    The only instance where DAO would not apply is in the case of a container managed entity bean. In this case, there is no need to write a DAO, as the container will persist the bean for you.
    - Saish
    "My karma ran over your dogma." - Anon

  • Question about ServiceLocator pattern

    Hi,
    I was wondering what would be the most approproate way to modify the serviceLocator pattern (from the core j2ee patterns book) to handle multiple initialContext? I.e, how do I modify the ServiceLocator to get the home from multiple remote servers?
    Do I get the client to pass in the InitialContext to be used?
    If I cache the homes - what should you use as the key? I.e. what can uniqeuly identify an InitialContext?
    Cheers,
    Nim

    An InitialContext is probably uniquely identified by the provider URL. I'd rather set up some kind of mapping, though, so that you just say "service this" and "service that", and the ServiceLocator, through configuration info, figures out what JNDI service to lookup as well as what to ask for.

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

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

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

Maybe you are looking for