I want to get an object by a static factory method, such as
Person p = Person.fromName("Jack");
class Person {
public static Person fromName(String name){
return new Person(name);
}
}
but fromName() method is not thread safe, (fromName() is just an example, this kind of method will occur error when it’s running in my program) however, it’s inefficient if synchronized this method because multiple threads should call this method concurrently. Is there any suggestion to fix it?
Your problem seems unsolvable when you say that
A) the method is not thread safe (thus needs to be used in a synchronized manner) and
B) it may not be synchronized due to efficiency reasons.
The only advice I can give you is to perform as fine grained syncrhonization as possible, i.e. only synchronize over thread-unsafe parts of the method.
If for instance statement
S1needs to be performed atomically together withS2you could instead of doingdo