Reputation: 1305
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?
Upvotes: 3
Views: 2568
Reputation: 421090
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 S1
needs to be performed atomically together with S2
you could instead of doing
public synchronized static Person fromName(String name){
...
S1;
S2;
...
return ...;
}
do
public static Person fromName(String name){
...
synchronized (lock) {
S1;
S2;
}
...
return ...;
}
Upvotes: 1
Reputation: 1502106
If you've got code which is unsafe to execute in multiple threads concurrently, but you want to call it from multiple threads, it sounds like you really only have two options:
You haven't given any information which would suggest which of these is most appropriate in your situation. (Have you measured the performance hit of synchronization? Have you tried to make it thread-safe?)
Upvotes: 2