如何在Java中正确地创建一个线程安全的Singleton Factory? [英] How to correctly make a thread safe Singleton Factory in Java?
问题描述
这是我第一次编写 Factory
类。下面是我的Factory类,我不确定这是否是制作线程安全的Singleton Factory类的正确方法。我将使用此工厂返回客户端的实例?
This is the first time I am writing a Factory
class. Below is my Factory class, I am not sure whether this is the correct way of making thread safe Singleton Factory class or not. I will be returning instance of my Client using this factory?
public class ClientFactory {
private static ClientFactory instance = null;
private ClientFactory() {
}
public static ClientFactory getInstance() {
if (instance == null)
{
instance = new ClientFactory();
}
return instance;
}
public IClient getClient() {
return new TestClient();
}
}
这是我的TestClient类 -
And here is my TestClient class -
public class TestClient implements IClient {
}
这就是我将如何使用我的工厂 -
And this is how I am going to use my factory -
IClient client = ClientFactory.getInstance().getClient();
推荐答案
实际上你的工厂不是线程安全的,因为在竞争条件下,您可以在应用程序中拥有多个ClientFactory。让我们假设两个线程:
In fact your factory isn't thread safe, because in race condition you can have more than one ClientFactory living in application. Lets assume two threads:
- ThreadA正在评估条件'if(instance == null)'并且实例为null,因此它输入语句
- ThreadB正在评估条件'if(instance == null)'并且实例为null(因为A没有实例化它),所以它输入语句
- ThreadA创建新的ClientFactory()并返回它
- ThreadB创建新的ClientFactory()并返回它
- 现在我们有多个应用程序中的ClientFactory。当然,其他线程试图在一段时间后检索实例将始终返回单个实例。
- ThreadA is evaluating condition 'if (instance == null)' and instance is null, so it enters statement
- ThreadB is evaluating condition 'if (instance == null)' and instance is null (because A didn't make to instantiate it), so it enters statement
- ThreadA creates new ClientFactory() and returns it
- ThreadB creates new ClientFactory() and returns it
- Now we have more than one ClientFactory in application. Of course other threads trying to retrieve instance some time later will always return single instance.
在我看来,编写单例的最简单方法Java是使用枚举。在你的情况下,它将看起来:
In my opinion the easiest way to write singleton in Java is to use enum. In your case it will looks:
public enum ClientFactory {
INSTANCE;
public Company getClient() {
return new Company();
}
}
用法:
ClientFactory.INSTANCE.getClient()
这篇关于如何在Java中正确地创建一个线程安全的Singleton Factory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!