jeudi 12 mars 2015

Thread safety in java for static methods



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 synchronized Object getSomething()
{
return MyClass._class2.someMethod();
}
}


I have read a few posts explaining thread safety for static methods but I have a few questions:




  1. 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?




  2. Does returning an object of the MyClass class in both the static methods cause any violation of thread-safety?






Aucun commentaire:

Enregistrer un commentaire