单线器的线程安全

时间:2012-02-08 16:41:16

标签: web-services design-patterns java-ee thread-safety

所以我想说我有一个用Spring创建的单例,MyWebService。 MyWebService的目标是返回一个MyObject。

编辑:当我提交一个非线程安全的Object SomeBuilder并用它创建对象MyObject时,我猜这很危险。但是:如果我交出工厂,每次调用每个方法都会实例化一个新的SomeBuilder对象,我想我是安全的?

@Webservice
public class MyWebService {
private final SomeFactory someFactory;
private final SomeBuilder someBuilder;

  public MyWebService(SomeFactory someFactory, SomeBuilder someBuilder){
    this.someFactory=someFactory;
    this.someBuilder=someBuilder;
   }
    public MyObject getSomeObject(SomeArgs someArgs){
    //this is threadsafe?
   SomeBuilder newlyCreatedBuilder=  someFactory.createObjectBuilder();
return   newlyCreatedBuilder.getMyObject(someArgs);


//where as this is dangerous?
return someBuilder.getMyObject(someArgs);

}
}

1 个答案:

答案 0 :(得分:0)

是的,只要那些其他实现也是线程安全的,就可以在单例中使用对工厂或任何其他java类的引用。