春豆螺纹安全 [英] Spring bean thread safety

查看:68
本文介绍了春豆螺纹安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在声明一个Java类的Spring bean,该类被用作创建对象的工厂.我想从不同的线程使用该工厂,我遇到的问题是,当线程尝试使用工厂创建对象时,它们被阻塞.

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.

据我所知,默认情况下春豆是单身人士,这就是我想要的.我希望工厂成为单身人士,但我想使用来自不同线程的该工厂来创建对象.工厂中的方法createObject()未同步,因此我不太清楚为什么会出现此同步问题.

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?

这是工厂的Java代码:

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

}

推荐答案

按照编写,似乎没有此类需要线程安全的任何内容.每次调用createObjects时,都会创建一个新的ConfigurableObjects List.在该列表中,添加单个SomeObject bean,然后将其返回.

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.

一个问题:SomeObject实例本身应该是单例吗?如果是这样,那么您需要保存它,并且只有在它为null时才调用getBean.

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

在这种情况下,您需要像我所示的那样同步对CreateObjects的访问.

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

这篇关于春豆螺纹安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆