views:

114

answers:

3

We have a spring application (single-threaded by design). We want to adapt it to be multi-threaded. One Idea was to create a parent thread and spawn different threads which would instantiate their own app context and run in parallel. (Memory and cpu are not a concern as of now). I am not sure how singletons are realized in spring. Does spring use a static reference and return this or uses some sort of cache/map (which is non-static/non-singleton and context specific) where it does a lookup? This would help me decide whether or not to change the config-xml. Any ideas please.

+3  A: 

Spring singleton beans are instantiated once per application context. That is, if you create many application contexts from the same config, they'll have different instances of singleton beans.

If you want them to share a single instance of a singleton bean, you can declare it in the parent application context and supply your multiple contexts with that parent context when you create them.

axtavt
+1, although the use of the term singleton here is misleading. They are singletons within application context scope, but not beyond that.
Rob H
+2  A: 

Why to you need multiple application contexts to make an application multi-threaded? Multiple threads can use the same context perfectly well.

Update: Take a look at spring batch

Bozho
And that would involve introduction of synchronized sections, which are a pain point especially with code for which there are no unit tests
questzen
you can't avoid the synchronized sections if you want to modify the same data.
Bozho
+1  A: 

It seems to me that you really need to look at what your singleton beans actually are doing and what their function will be in a multithreaded environment. I wouldn't try and update your application contexts to fit your threading model, but rather the lifecycle of the beans to be appropriate.

  • If they are truly singleton and are threadsafe by nature, then just use them as is with multiple threads.
  • If they are not threadsafe, then should they continue to be spring singletons in your new, multithreaded implementation? It may more sense to update them to be non-singleton beans that are instantiated per thread then to try and tie your entire application contexts to particular threads.
Pete