假设这是从多个线程调用的,以下测试方法是否是线程安全的?有时 println 语句显示“null”。
这个想法是返回一个映射,该映射将根据提供的标识符按需创建 bean。请注意,这只是一个简单的示例,用于说明一个类似的现实生活场景,其中一个 bean 使用相同的方法没有满足其依赖关系(例如,value.x 为空)。对于加分,是否有另一种(更好的)方法可以达到相同的效果?
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.oanda.bi.rm.test.AnnotationConfigTest.Config;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
public class AnnotationConfigTest {
@Resource
Map<String, Value> map;
@Test
public void test() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool( 10 );
for ( int i = 0; i < 10; i++ ) {
service.execute( new Runnable() {
@Override
public void run() {
// Is this thread-safe?
Value value = map.get( "value" );
// Sometimes null!
System.out.println( value.x );
}
} );
}
service.shutdown();
service.awaitTermination( 1, TimeUnit.MINUTES );
}
public static class Value {
@Resource
protected Integer x;
}
@Configuration
public static class Config {
@Bean
public Integer x() {
return 1;
}
@Bean
@Scope("prototype")
public Value value() {
return new Value();
}
@Bean
@SuppressWarnings("serial")
public Map<String, Value> map() {
// Return a Spring agnostic "bean factory" map
return Collections.unmodifiableMap( new HashMap<String, Value>() {
@Override
public Value get( Object obj ) {
String key = (String) obj;
if ( key.equals( "value" ) ) {
// Create new bean on demand
return value();
}
// Assume other similar branches here...
return null;
}
} );
}
}
}
更新
鉴于来自 Biju Kunjummen 的富有洞察力的反馈,我尝试了一种直接使用应用程序上下文的不同方法,但它仍然失败,将返回空值。这次我使用的是 Function 抽象而不是 Map ,这似乎更合适:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.google.common.base.Function;
import com.oanda.bi.rm.test.AnnotationFunctionConfigTest.Config;
/**
* Unit test that tries to perform the same pattern as {#link ResourceConfig} and ensure
* thread safety.
*
* @see http://stackoverflow.com/questions/12700239/thread-safety-of-calling-bean-methods-from-returned-annonymous-inner-classes/12700284#comment17146235_12700284
* @see http://forum.springsource.org/showthread.php?130731-Thread-safety-of-calling-Bean-methods-from-returned-annonymous-inner-classes&p=426403#post426403
* @author btiernay
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
public class AnnotationFunctionConfigTest {
@Resource
Function<String, Value> function;
@Test
public void test() throws InterruptedException {
final int threads = 10;
ExecutorService service = Executors.newFixedThreadPool( threads );
for ( int i = 0; i < threads; i++ ) {
service.execute( new Runnable() {
@Override
public void run() {
Value value = function.apply( "value" );
Assert.assertNotNull( value.x );
}
} );
}
service.shutdown();
service.awaitTermination( 1, TimeUnit.MINUTES );
}
public static class Value {
@Resource
protected Integer x;
}
@Configuration
public static class Config {
@Bean
public Integer x() {
return 1;
}
@Bean
@Scope("prototype")
public Value value() {
return new Value();
}
@Bean
public Function<String, Value> function() {
// Return a Spring agnostic "bean factory" function
return new Function<String, Value>() {
@Autowired
private ApplicationContext applicationContext;
@Override
public Value apply( String key ) {
if ( key.equals( "value" ) ) {
// Create new bean on demand
return applicationContext.getBean( key, Value.class );
}
// Assume other similar branches here...
return null;
}
};
}
}
}
有人愿意评论为什么这似乎仍然不安全吗?
更新
这看起来可能是一个 Spring 错误。我提交了一张jira票: