Announcement Announcement Module
No announcement yet.
trying to wrap my head around spring. Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • trying to wrap my head around spring.

    I'm sure you must get a million of these posts a week. I am still trying to wrap my head around spring after reading J2ee without ejb.


    Let's say I have a class called search handler. It conducts some search, collects the results, does some filtering and returns a result set.

    With spring, I would get an instance of the search handler from the beanfactory. I am assuming that it would be a singleton since the class would not have to keep any state over function calls.

    However, how does this work from a threading point of view. ie. Lets say the method takes 10 seconds on average to complete, and there are 5 calls to it in a matter of milliseconds. Does it perform all these at once? Only if the method was synchronized would it have to wait, correct? I've always found it very confusing that one object could handle, ie 1000 requests per second.

    How does this all work?

    Thank you greatly!


  • #2
    The singleton does need to be thread-safe. However, that doesn't necessarily mean that its methods must be synchronized. If the object is stateless, there's no contention for shared data, so an arbitrary number of threads can execute inside it at once.

    This doesn't have anything to do with Spring, really. It's just how multithreaded programming works.


    • #3
      To just expand on the earlier answer, you'd pass your search criteria into your singleton method. eg:

      private SearchDao search;
      public List search(String name) {
      As the method does not modify any object-level properties, there is no need to worry about threading issues. Your DAOs are almost always the same, and just delegate to a RDBMS which takes care of synchronisation.

      On the other hand, this method would be a problem:

      private Map bankAccounts = new MashMap();
      public void deposit(Long accountNumber, float amount) {
      Hope that clears it up for you.


      • #4
        The caller would probably be configured by Dependency Injection. Thus it would hold a reference, rather than need to call getBean() on the factory (although of course that would work as well).

        As Ben points out, a single object will be the best solution for a stateless service.

        Spring also supports pooling a la SLSBs, for more complex threading scenarios, but they're actually pretty rare for this kind of service. Unlike EJB, Spring can provide pooling for any POJO.

        But as Ben also pointed out, the question is not really Spring-specific.