Announcement Announcement Module
Collapse
No announcement yet.
Why is everything singleton ? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Why is everything singleton ?

    Hi,
    I am new to Spring framework. I saw some of the examples that come with spring's download. In Spring manual, it says, if you dont specify what kind of object it is, it will default to singleton. In the Jpetstore example that comes with spring , none of the configuration files specify singleton attribute. Does that mean all objects are singletons ? If yes, why is that ?

    Thanks for your reply.

    VG

  • #2
    One reason is that it's the simplest thing that works.

    There's no point creating instances of the same object if that object is threadsafe -- it just needlessly uses CPU doing the instantiation and garbage collection.

    Comment


    • #3
      Thanks for your reply.
      I have one more question though.
      What about the thread synchornization (as objects are thread safe), that will also have impact on CPU.

      Comment


      • #4
        Originally posted by vinaygajjar
        Thanks for your reply.
        I have one more question though.
        What about the thread synchornization (as objects are thread safe), that will also have impact on CPU.
        No. You don't have to synchronize stuff for it to be thread safe, just avoid member variables. This is a common pattern. Remember that standard things like servlets are also singletons and you have to avoid using member variables there. It's the same concept in Spring. Also Struts. etc

        Bob

        Comment


        • #5
          Re: Why is everything singleton ?

          Originally posted by vinaygajjar
          ...none of the configuration files specify singleton attribute. Does that mean all objects are singletons ? If yes, why is that ?
          That's correct, the default is singleton.
          Originally posted by Cowboy Bob
          You don't have to synchronize stuff for it to be thread safe, just avoid member variables
          A better statement is not to use member variables to hold convesrational state. They work just fine for delegates and services.

          Comment

          Working...
          X