I have the following code
//EDIT :- updated code with @Riaz's answer ( this code should be thread -safe now )
public final class MyClass
{
private static MyClass2 _class2;
private MyClass()
{
}
public static synchronized MyClass CreateMyClass1(String arg0 , ArrayList<MyClass3> class3) throws Exception
{
MyClass myClass = new MyClass();
_class2 = new Class2(arg0 , class3);
return myClass;
}
public static synchronized MyClass CreateMyClass2(InputStream arg0 , ArrayList<MyClass3> class3) throws Exception
{
MyClass myClass = new MyClass();
_class2 = new Class2(arg0 , class3);
return myClass;
}
//EDIT :- added a third method that accesses methods of the _class2 object
public Object getSomething() //don't need synchronized for methods that don't change the state of the object
{
return MyClass._class2.someMethod();
}
public synchronized Object doSomethingToClass2()
{
//change state of the _class2 variable
}
}
I have read a few posts explaining thread safety for static methods but I have a few questions:
From what I understand, unless two threads can change the state of a shared mutable object, I don't need to worry about thread safety. (Assuming that I am not leaking the "this" reference.)
So when using MyClass, can thread1 call CreateMyClass1 and thread2 call CreateMyClass2 which will mean that the _class2 variable will be changed by thread2 which is what I want to avoid. Will making _class2 as volatile prevent this? If yes, I am not sure how static volatile will be interpreted by the JVM? Will this be enough to make MyClass thread-safe?
Does returning an object of the MyClass class in both the static methods cause any violation of thread-safety?