Is creating a new object a thread safe

Is the getCopyOf method the following code in streaming mode in java? I'm not sure if building an object is an 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;
    }
}
+4
source share
2 answers

In your example, yes, String is immutable and inaccessible, your constructor will be thread safe.

However, if you replace the string with an arbitrary object (say, another class) and you have setters for these objects, then you may run into thread safety problems. Therefore, in a more general answer to your question, the designers, like any other methods, do not offer an explicit thread safety mechanism, which is up to you to make sure that your operations are safe in the thread.

, .

+1

, this constuctor. .

public class MyClass {
    public MyClass(Object someObject) {
        someObject.someMethod(this); // can be problematic
    }
}

. , , .

: Java

0

Source: https://habr.com/ru/post/1541785/


All Articles