简体   繁体   中英

Is it necessary to synchronize a factory method that returns a new instance of a class in java

Today i was asked to write up a factory to get a new instance of a class. I did this quite easily.

One of my all knowing colleagues looked at my code and told me to synchronize the method that does this.

I asked him why and he replied that is the right thing to do. (offered no explanation when asked) I did not do it as i believe since i'm not manipulating the state of the object, i don't have to synchronize it.

I just want to clarify whether i was right. If i was wrong, can someone explain why it is necessary to synchronize.

eg

private static Map<String, IProduct> products = new HashMap<String, IProduct>();

public IProduct getInstance(code){
   return products.get(code).create();
}

Edit based on comments :

  • I can't give the full code as I don't have access to it now. I will do it when I get back to work.
  • products is a Map<String, IProduct>
  • create() is a method on the class implementing IProduct . This method just returns a new instance of the implementing class.
  • the instance put into the static map is only to be used to 'new' up an instance of Product .

I'm going to guess that products is a Map and that it is not synchronized (either by its implementation or via Collections.syncronizedMap() ). If whatever is stored in products is mutable, then it is possible that something else is going to be working with products while you are using get() and this could cause some issue.

Specifically, if whatever the class is that has a create() method is mutable, then in a parallel environment, some other thread could mutate the value retrieved from products after get() and before create() , which could cause problems (for instance, if create() can only be called a set number of times).

That said, you should press your colleague as to why they want you to synchronize the method. They should have a specific reason, and if they can't explain it to you, their reason either isn't good enough or they don't understand it enough.

如果同步工厂方法,我们将确保在一个线程检索新实例的同时,其他线程不会执行相同的操作。相反,任何并行线程都将等待其轮换并获取已创建的实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM