Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean references across multiple thread

I have come across a scenario as below:

MyBean - Defined in XML Configuration.

I need to inject MyBean into multiple threads. But my requirements is: 1) The reference retrieved in two different threads should be different 2) But I should get the same reference irrespective how many times I retrieve bean from single thread.

Eg :

Thread1 {

    run() {
        MyBean obj1 = ctx.getBean("MyBean");
        ......
        ......
        MyBean obj2 = ctx.getBean("MyBean");
    }
}

Thread2 {

    run(){
        MyBean obj3 = ctx.getBean("MyBean");
    }
}

So Basically obj1 == obj2 but obj1 != obj3

like image 831
user2039968 Avatar asked Feb 04 '13 14:02

user2039968


2 Answers

You can use the custom scope named SimpleThreadScope.

From the Spring documentation :

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Section 3.5.5.2, “Using a custom scope”.

Here an example of how to register the SimpleThreadScope scope :

Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);

Then, you'll be able to use it in your bean's definition :

<bean id="foo" class="foo.Bar" scope="thread">

You can also do the Scope registration declaratively :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="thread">
                    <bean class="org.springframework.context.support.SimpleThreadScope"/>
                </entry>
            </map>
        </property>
    </bean>

    <bean id="foo" class="foo.Bar" scope="thread">
        <property name="name" value="bar"/>
    </bean>

</beans>
like image 170
Jean-Philippe Bond Avatar answered Sep 27 '22 16:09

Jean-Philippe Bond


What you require is a new Thread Local custom scope. You can either implement your own or use the one here.

The Custom Thread Scope module is a custom scope implementation for providing thread scoped beans. Every request for a bean will return the same instance for the same thread.

like image 42
Aravind Yarram Avatar answered Sep 27 '22 16:09

Aravind Yarram