初始化一个我想在多个线程之间共享的静态对象的最佳方法是什么

时间:2019-02-15 19:59:29

标签: java

编辑:在此处添加更多上下文和代码:

目前这是我所拥有的:

public class MyClass{

   private static MyClass2 mySharedObject = null; //this is the object that I want to share across m

   private SomeRandomClass someRandomClass; 

   public MyClass(MyClass3 object3, MyClass4 object4, SomeRandomClass someRandomClass){


 /* it just so happens that it is guaranteed that someRandomClass, no 
    matter which thread creates it, will have the same value.  But the value is not known in design time and hence I can't move this initialize code to the static {} block, as suggested by many folks.  One thing that I can do is move the creation of this sharedObject outside MyClass and do it before any threads actually use it.  Unfortunately, I am dealing with a legacy code here and didn't want to do that change and that's why asked if the approach I presented is good enough or there is something better? */  


        this.someRandomClass = someRandomClass;

        synchronized(mySharedObject){

              if(mySharedObject ! =null){
                 mySharedObject = new MyClass2(someRandomClass);//It doesn't matter which thread wins to create this object. I just need a valid instance of someRandomClass to create mySharedObject.  Once it is created, I can use it for all the threads.
               }

        }

   }

}

有更好的方法吗? PS:我不想在MyClass的构造函数中传递此共享对象,并且/或者我不想将MyClass2设置为单例。

谢谢

1 个答案:

答案 0 :(得分:1)

使用静态初始化程序块。

public class MyClass {
    private static MyClass2 mySharedObject;

    static {
        mySharedObject = null; // whatever value here
    }

    // The rest of MyClass
}

编辑:从您的评论中,另一种方法是,在开始尝试进行的任何并发过程之前,先在外部设置mySharedObject的值:

/* MyClass.java */

public class MyClass {
    private static MyClass2 mySharedObject = null;

    public static SetSharedObject(MyClass2 sharedObject) {
        mySharedObject = sharedObject;
    }

    // The rest of the class
}

/* Elsewhere.java */

MyClass2 sharedObject = new MyClass2(someRandomClass);
MyClass.SetSharedObject(sharedObject);    

// Do whatever you do with MyClass concurrency