Reputation: 5596
Is method getCopyOf in following code thread-safe in java ? I am not sure if construction of object is atomic operation.
public class SomeClass {
private final String arg1;
private final String arg2;
public SomeClass(String arg1, String arg2){
this.arg1= arg1;
this.arg2 = arg2;
}
public SomeClass getCopyOf() {
return new SomeClass(this.arg1,this.arg2);
}
public String getArg1(){
return arg1;
}
public String getArg2(){
return arg2;
}
}
Upvotes: 4
Views: 1527
Reputation: 7712
In your example yes, String being immutable and not accessible then your constructor will be thread safe.
However if you replace the string with an arbitrary object (say another class) and have setters for these objects then you may run into problems regarding thread safety. So in a more general answer to your question, no, constructors, like any other methods, offer no explicit thread safety mechanism it is up to you to make sure your operations are thread safe.
Even worst should your class contain static fields then the constructor itself may have thread safety problems with itself.
Upvotes: 1
Reputation: 30528
It is thread safe until you delegate the this
reference from the constuctor. After that it is no longer thread safe.
public class MyClass {
public MyClass(Object someObject) {
someObject.someMethod(this); // can be problematic
}
}
This is just one example I think you can imagine some scenarios where thread safety issues can occur.
Related: Constructor synchronization in Java
Upvotes: 0