user2039968
user2039968

Reputation: 83

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

Upvotes: 8

Views: 2730

Answers (2)

Jean-Philippe Bond
Jean-Philippe Bond

Reputation: 10649

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>

Upvotes: 10

Aravind Yarram
Aravind Yarram

Reputation: 80166

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.

Upvotes: 2

Related Questions