Saturday, April 28, 2012

Spring Singleton...Use it in right way or get messed

      Content of this post expects that you are already familiar with Core Spring Concepts like IOC etc. Other very important aspect of the Spring is its Scopes of the Bean which we define in the configuration either via Annotation or via xml.

  • What Is Spring:
    But to give little brief, Spring is a framework which we can use to create an architecture where Classes and its dependencies can be fulfilled using the Declaration rather than Handcoding. So basically, most objects that you use/need for ur program during runtime, will come from the Factory which we known as Spring Framework. I know, I am using some layman terminology here, but I think this way it will be lottle clear to beginners.

     So, you will create most important objects of you application like some Service Objects, some DB connection/pool objects etc. via Spring. And it has its own advantage which you can get know from many online tutorials.

  • What is Bean:   Classes which are configured to get created via Spring. Every instance of such classes are called "bean"

       Want to focus on "Singleton" scoped bean here. It makes sure that only one instance of that bean will be present in the "Spring Container" where it is defined. Please dont get fooled by thinking that it is same Singleton object in our regular day to day life code.
        Singleton scope does have an advantage that it can give:
           => High throughput: because the same object is getting referred and used every time its required, so there is no need to create a new instance again and again.
            => Low Memory Foot print: because there is no need to new instance again once a instance got created.

         But with aforesaid advantages, developer must also take due care else will fall in a big trouble in no time. As you know, only single instance is available in that container during runtime, so everytime when it is referred or asked for, that very instance will be returned by Spring factory (Context).
      Here come the possible gotcha, where same bean might be getting referred by multiple threads performing may same/different method calls on that object.So, by-chance, if there are any state, that you maintain in that singleton object, may be visible to other method calls as well. And this might be un-desirable.
       By saying state we mean, some value in the instance variables of the bean. One issue I sufferred very recently can be referred by clicking here.