开发者

Spring bean thread safety

I am declaring a Spring bean for a Java class that is used as a factory to create objects. I want to use this factory from different threads, the problem I am experienced is that threads are blocked when they try to create an object using the factory.

As far as I know spring beans are singletons by default, and this is what I want. I want the factory to be a singleton but I would like to create object using this factory from different threads. The method createObject() in the factory is not synchronized, therefore I do not understand very well why I'm having this synchronization issue.

Any suggestions about which is the best approach to achieve this?

This is the java code for the factory:

public class SomeFactory implements BeanFactoryAware {

private BeanFactory beanFactory;

public List<ConfigurableObjects> createObjects() {
    List<ConfigurableObjects> objects = new ArrayList<ConfigurableObjects>();
    objects.add((SomeObject)beanFactory.getBean(SomeObject.class.getName()));

    return objects;
}

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    this.beanFactory = beanFactor开发者_JAVA技巧y;
}

}


As written, it doesn't appear that there's anything in this class that needs to be thread safe. You create a new ConfigurableObjects List each time you call createObjects. To that List you add a single SomeObject bean and then return it.

One question:is the SomeObject instance supposed to be a singleton itself? If so, then you need to save it and only call getBean if it's null like so.

private SomeObject someObjectInstance = null;

public synchronized List<ConfigurableObjects> createObjects() {
  List<ConfigurableObjects> objects = new ArrayList<ConfigurableObjects>();
  if (someObjectInstance = null)
  {
    someObjectInstance = (SomeObject)beanFactory.getBean(SomeObject.class.getName());        
  }

  objects.add(someObjectInstance);
  return objects;
}

In this case, you would need to synchronize access to CreateObjects as I've shown.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜