Java: static factory method and thread safe

I want to get an object using a static factory method like

Person p = Person.fromName("Jack");

class Person {
    public static Person fromName(String name){
        return new Person(name);
    }
}

      

but methodName () is not thread safe, (fromName () is just an example, such a method will occur when run in my program), however it is inefficient if this method is synchronized because multiple threads must call this method at the same time. Is there a suggestion to fix this?

+3


source to share


2 answers


Your problem seems insoluble when you say that

  A) the method is not thread safe (therefore it must be used synchronously) and

  B) it cannot be synchronized for efficiency reasons.

The only advice I can give you is to perform as fine-grained synchronization as possible, i.e. only sync with unsafe parts of the method.



If, for example, a statement is to S1

be executed atomically along 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 ...;
}

      

+1


source


If you have code that is unsafe to execute on multiple threads at the same time, but want to call it from multiple threads, it looks like you really only have two options:

  • Make thread safe
  • Let's take serializing calls through sync


You have not provided any information that would suggest which one is most appropriate for your situation. (Have you measured sync sync performance? Have you tried to make it thread safe?)

+2


source







All Articles