Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring singleton beans across multiple application contexts

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.

like image 388
questzen Avatar asked Dec 30 '22 02:12

questzen


2 Answers

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.

like image 174
axtavt Avatar answered Dec 31 '22 15:12

axtavt


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

like image 43
Bozho Avatar answered Dec 31 '22 14:12

Bozho