繁体   English   中英

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

[英]What is the best way to initialize a static object that I want to be shared across multiple threads

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

目前这是我所拥有的:

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 作为单例。

谢谢

使用静态初始化块。

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

暂无
暂无

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

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