编辑:在此处添加更多上下文和代码:
目前这是我所拥有的:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句