简体   繁体   English

春豆螺纹安全

[英]Spring bean thread safety

I am declaring a Spring bean for a Java class that is used as a factory to create objects. 我在声明一个Java类的Spring bean,该类被用作创建对象的工厂。 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. 据我所知,Spring bean默认情况下是单例,这就是我想要的。 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. 工厂中的方法createObject()未同步,因此我不太清楚为什么会有同步问题。

Any suggestions about which is the best approach to achieve this? 关于哪种方法是实现此目标的最佳方法有何建议?

This is the java code for the factory: 这是工厂的Java代码:

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 = beanFactory;
}

} }

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. 每次调用createObjects时,都会创建一个新的ConfigurableObjects List。 To that List you add a single SomeObject bean and then return it. 向该列表中添加单个SomeObject bean,然后将其返回。

One question:is the SomeObject instance supposed to be a singleton itself? 一个问题:SomeObject实例本身应该是单例吗? If so, then you need to save it and only call getBean if it's null like so. 如果是这样,那么您需要保存它,并且仅当它为null时才调用getBean。

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. 在这种情况下,您将需要同步对CreateObjects的访问,如图所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM