12 Replies Latest reply: Mar 18, 2011 4:24 PM by 796440 RSS

    Singleton pattern

    Prem
      Hi,

      Could any one tell me benefits of singleton pattern in any web application ?
        • 1. Re: Singleton pattern
          796440
          Google can.
          • 2. Re: Singleton pattern
            Prem
            Please dnt suggest that option as I did it but not satisfied. If you are having any other suggestions or links which can help me to understand that how singleton pattern can be helpful for web application.
            • 3. Re: Singleton pattern
              796440
              Prem wrote:
              Please dnt suggest that option
              It is exactly the correct answer for the question you asked. This forum is not a research service, and we cannot read your mind.
              as I did it but not satisfied.
              Then you need to provide more details.
              If you are having any other suggestions or links which can help me to understand that how singleton pattern can be helpful for web application.
              Nope. How can I possibly know what you've read or in what way you found it insufficient to answer your question or what you found hard to understand? Since I don't know that, any "other" information I provide would just be a guess and could very well be a repeat of what you've already read and didn't understand. I'm not going to waste my time like that.
              • 4. Re: Singleton pattern
                gimbal2
                Prem wrote:
                Hi,

                Could any one tell me benefits of singleton pattern in any web application ?
                If it benefits in the implementation of the requirements you have and it makes to code readable / easy to maintain. Generic answer for generic questions.
                • 5. Re: Singleton pattern
                  Prem
                  Ok .. Let me take you into deeper..

                  Suppose I have a servlet say MainServlet to which is basically controller for my web application. Now suppose there is one more class say MainServletHelper class having singleton feature and having various method say authenticate(), getEmployeeList() etc.

                  Now suppose user "XYZ" logs in , and getEmployeeList() method is suppose to be executed but list is displayed only basis of "XYZ" role. If suppose "XYZ" is team leader then he can view only team leader's list.

                  For above control will be like this

                  request->doPost()->MainServletHelper.getInstance().getEmployeeList()

                  Similarly if suppose another user with different role logs in the control flow for this user will be same as for "XYZ" but when

                  MainServletHelper.getInstance().getEmployeeList() is get executed , as it is getInstance is static method and instance is also static then how different list is get displayed to different user.


                  Perhaps I might not be able to escalate the problem in above lines , but I just want to know how singleton pattern behaves exactly ?
                  • 6. Re: Singleton pattern
                    796440
                    Prem wrote:
                    MainServletHelper.getInstance().getEmployeeList() is get executed , as it is getInstance is static method and instance is also static then how different list is get displayed to different user.
                    If the list is accessed through a member variable lacking proper synchronization, then multiple concurrent requests might see or corrupt each others' values.

                    If only local variables are involved, and those variables don't refer to shared objects (or if access to those shared objects is properly synchronized), then there is no corruption, because local variables are not shared across threads.
                    but I just want to know how singleton pattern behaves exactly ?
                    As I'm sure you can understand from any tutorial or google result, a Singleton's behavior is the same as any other instance of that class, and the only thing special about a Singleton is that it is, by definition, the only instance of that class that exists. Making something a singleton doesn't change its behavior.

                    Edited by: jverd on Mar 18, 2011 11:57 AM
                    • 7. Re: Singleton pattern
                      Prem
                      But if I am not wrong suppose

                      public class MainServletHelper
                      {
                      private static MainServletHelper instance;

                      public MainServletHelper getInstance()
                      {
                      If(instance ==null)
                      {
                      instance = new MainServletHelper ();

                      }

                      return instance;
                      }

                      public list getEmployeeList()
                      {
                      //Logic to render employee list.
                      }

                      }


                      }

                      In above code "instance" is static field , so whenever getInstance() method is called from MainServlet()'s doPost() method, "instance" is null then new object is created but now for second user ,"instance" is same as of previous user ?
                      • 8. Re: Singleton pattern
                        796440
                        Prem wrote:
                        But if I am not wrong suppose

                        public class MainServletHelper
                        {
                        private static MainServletHelper instance;

                        public MainServletHelper getInstance()
                        {
                        If(instance ==null)
                        {
                        instance = new MainServletHelper ();

                        }

                        return instance;
                        }

                        public list getEmployeeList()
                        {
                        //Logic to render employee list.
                        }

                        }


                        }

                        In above code "instance" is static field , so whenever getInstance() method is called from MainServlet()'s doPost() method, "instance" is null
                        No, it's only null the first time getInstance() is called. Or at least that would be the case if you used proper synchronization and properly declared getInstance() to be static. A non-static getInstance() method makes no sense. An even better approach than syncing would be to just instantiate it at the same point where you declare it.
                        then new object is created but now for second user ,"instance" is same as of previous user ?
                        Yes, but so what? Why do you think that will be a problem? In particular, after re-reading very closely what I wrote in my previous reply, why do you think that will be a problem?

                        Edited by: jverd on Mar 18, 2011 12:23 PM

                        Edited by: jverd on Mar 18, 2011 12:24 PM
                        • 9. Re: Singleton pattern
                          Prem
                          jverd wrote:
                          A non-static getInstance() method makes no sense.
                          I mistakenly forgot to write that one.

                          You mean to say that there must be synchronization suppose to be implemented ?

                          Edited by: Prem on Mar 18, 2011 12:39 PM
                          • 10. Re: Singleton pattern
                            796440
                            Prem wrote:
                            jverd wrote:
                            A non-static getInstance() method makes no sense.
                            I mistakenly forgot to write that one.

                            You mean to say that there must be synchronization suppose to be implemented ?
                            NO. I did not say that.

                            I said that IF you're going go have a method that checks for null, and then instantiates if it is null, THEN you must sync:
                            public class Single {
                              private static Single instance;
                            
                              public static synchronized Single getInstance() {
                                if (instance == null) {
                                  instance = new Single();
                                }
                                return instance;
                              }
                            }
                            I ALSO said that it's better to do it this way:
                            public class Single {
                              private static final Single instance = new Single();
                            
                              public static Single getInstance() {
                                return instance;
                              }
                            }
                            • 11. Re: Singleton pattern
                              Prem
                              I said that IF you're going go have a method that checks for null, and then instantiates if it is null, THEN you must sync:
                              What is the advantage of doing that ?
                              public class Single {
                              private static Single instance;
                              
                              public static synchronized Single getInstance() {
                              if (instance == null) {
                              instance = new Single();
                              }
                              return instance;
                              }
                              }
                              I ALSO said that it's better to do it this way:
                              public class Single {
                              private static final Single instance = new Single();
                              
                              public static Single getInstance() {
                              return instance;
                              }
                              }
                              Which one shall I use if it is to be used in web application ?
                              • 12. Re: Singleton pattern
                                796440
                                Prem wrote:
                                I said that IF you're going go have a method that checks for null, and then instantiates if it is null, THEN you must sync:
                                What is the advantage of doing that ?
                                The advantage is that it works, and not doing it may not work.

                                First, if multiple threads come in at the same time, without syncing, they can all get true for if (instance == null), and all of them will create new instances.

                                Second, even if the threads don't hit the method at the same time, threads are allowed to keep local copies of shared variables. Entering and exiting sync blocks forces reconciliation of local copies with main memory, but without it, each thread might never write the non-null value of the instance variable out to main mem, and even if it does, other threads might never read that value from main mem.

                                The second problem can also be prevented by declaring the instance variable to be volatile, because the meaning of volatile--the whole point of it--is to force every read and write of that variable to use the single main copy. The first problem would still remain however.

                                Finally, a thread that is constructing the singleton could assign the non-null reference before it finishes constructing it. That reordering of instructions is allowed, since within a single thread, the difference cannot be seen. Another thread might see a non-null value and a partially constructed (and hence not yet in a valid stat) instance.

                                So without syncing, you can end up with multiple copies of your singleton, and you can use the object when its in an invalid state because it hasn't yet been fully constructed.
                                I ALSO said that it's better to do it this way:
                                public class Single {
                                private static final Single instance = new Single();
                                
                                public static Single getInstance() {
                                return instance;
                                }
                                }
                                And the reason this way is better is because it is simpler, and because it avoids synchronization, which could cause a performance hit for contended locks here.
                                Which one shall I use if it is to be used in web application ?
                                I already told you which approach is better.

                                And the "in a web application" is meaningless. The type of the application rarely, if ever, has anything to do with which particular approach is chosen, for any design choice. What matters are the requirements of the specific use case. For any given design decision, your "web application" or my "voice quality tracking application" or somebody else's "CAD application" will probably use one approach in one area and another approach in another area.

                                It's like asking "are ints or doubles better for a web application?" It just makes no sense in that context--or rather with that lack of context.

                                Edited by: jverd on Mar 18, 2011 1:23 PM

                                Edited by: jverd on Mar 18, 2011 2:23 PM