Announcement Announcement Module
Collapse
No announcement yet.
Singleton vs. Prototype Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Singleton vs. Prototype

    I've now successfully deployed two applications based on the Spring Framework. I am constantly amazed at this software and the significant improvements I've made in application creation.

    Now that I've gotten some things out, I'm starting to develop some usage questions. My first is in the title. The Spring document, which is very comprehensive doesn't talk much about a, IMO, very fundamental feature of Spring's bean creation: Singleton vs. Prototype. I would like an expanded understanding of the implications of using one over the other, perhaps some scenarios to help select one over the other.

    For example, we I used Mark Eagle(?) article on Wiring open source applications as a starting point for the Persistence layer we have in our applications. I have a business object that contains a PersistenceService interface that is injected by Spring. A class that implemented this interface has serveral DAOs also injected by Spring.

    We had a bug where I passed an object containing some data to the persistence layer. This data object was passed in as a BaseData object(another interface). For ease of use, the implementation class of the PersistenceInterface had a class variable that I would cast BaseData to. For example, I would cast BaseData to CostData thereby gaining access to the specific getters of CostData. Again, this was done right at the beginning of a specific method just to simplify use.

    However, we had a problem that two simultaneous calls to this PersistenceService(user1 and user2) would cause the data of user1 to appear in user2's call.

    It appear that since the same instance of PersistenceService was being returned, and this variable that held a reference to BaseData was a class instance variable, that this data was overlapping.

    Would it be safe to say that instance variables of singleton Spring returned beans are not threadsafe? I removed the casting, in essence, stopped using the class variable and stuck to using the object that was passed in as well as variables created locally in the method and the problem seemed to go away.

    Are there any nuances of Singleton and Prototype use that can be shared?

    Thanks!

  • #2
    Would it be safe to say that instance variables of singleton Spring returned beans are not threadsafe?
    No. Whether or not access to instance variables of a singleton is thread safe is entirely a function of the design of the class and has nothing to do with whether it is managed by Spring or anything else for that matter.

    Ollie

    Comment

    Working...
    X