I'm trying to understand whether this is thread safe. I believe it is, but someone recently brought into question the thread safety of this method.
Let's say I have some factory FactoryA
that give us a class which implements the following interface:
public abstract class MyFactory {
private ObjectA object;
public void init(ObjectA object){
_object = object;
}
}
So, we have something like
public class FactoryA extends MyFactory {
static final createFactoryClass(String name) {
// ...ignorning safety checks for brevity
return MY_MAP.get(name).newInstance();
}
}
Now, I have some method in another class that takes the factory and gives back a map of possible classes:
public class OtherClass {
private static FactoryA _factory = new FactoryA();
private static final Map<String, SomeClass> MY_MAP = new ImmutableMap.Builder<String, MyClass>()
.put("foo", _factory.createFactoryClass("foo"));
private SomeObject myMethod(ObjectA objectA, SomeObject someObject) {
MY_MAP.get(someObject.getString()).init(objectA);
}
}
The question is whether the init
method is thread safe. The map is initialized only once, so even though it's stored in an immutable structure, if two threads call it with different ObjectA
, is it possible for the wrong class to use the wrong ObjectA
?
Can I just fix this possible problem by doing the following?
private static synchronized myMethod(...) {}