AfterWorkGuinness AfterWorkGuinness - 5 months ago 35
Java Question

Are static factory methods thread safe?

A similar but different question has been asked before here Are method parameters thread safe in Java? , but did not address my specific concern.

In the case of a static factory method like the below, is it possible for ThreadA to pass in its params A,B,C and ThreadB to pass in its params D,E,F and the instance that is returned was constructed using the params from the wrong thread?

public static Foo createFooBar(String first, String second, String third) {

return new Foo(first, second, third);
}

private Foo(String first, String second, String third)
{
//do stuff
}

Answer

In the example you've provided, No: There is no risk of race conditions between multiple threads accessing the same methods.

There would, however, be a risk if the code were written like this:

private static String workingString;

public static Foo createFooBar(String first, String second, String third) {

   return new Foo(first, second, third);
}

private Foo(String a, String b, String c) {
    workingString = a;
    //do stuff
    doSomethingWith(workingString);
    //do stuff
}

Because in this situation, if multiple threads modify the value of workingString, you don't have a guarantee that the doSomethingWith(workingString) call is working with a, like the method as written implies.