From 502366bb108216ae3dfc24164b98e9b62aaa4840 Mon Sep 17 00:00:00 2001 From: guide Date: Wed, 6 Jan 2021 15:46:32 +0800 Subject: [PATCH] =?UTF-8?q?[fix]=E5=8D=95=E4=BE=8B=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E7=9A=84=E5=B7=A5=E5=8E=82=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../javaguide/factory/SingletonFactory.java | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/rpc-framework-common/src/main/java/github/javaguide/factory/SingletonFactory.java b/rpc-framework-common/src/main/java/github/javaguide/factory/SingletonFactory.java index 7a02ce8..ed6a837 100644 --- a/rpc-framework-common/src/main/java/github/javaguide/factory/SingletonFactory.java +++ b/rpc-framework-common/src/main/java/github/javaguide/factory/SingletonFactory.java @@ -11,30 +11,25 @@ import java.util.Map; * @createTime 2020年06月03日 15:04:00 */ public final class SingletonFactory { - private static volatile Map objectMap = new HashMap<>(); + private static final Map OBJECT_MAP = new HashMap<>(); private SingletonFactory() { } public static T getInstance(Class c) { String key = c.toString(); - Object instance = objectMap.get(key); - if (instance == null) { - synchronized (SingletonFactory.class) { - instance = objectMap.get(key); - if (instance == null) { - try { - instance = c.getDeclaredConstructor().newInstance(); - objectMap.put(key, instance); - } catch (IllegalAccessException | InstantiationException e) { - throw new RuntimeException(e.getMessage(), e); - } catch (NoSuchMethodException | InvocationTargetException e) { - e.printStackTrace(); - } + Object instance; + synchronized (SingletonFactory.class) { + instance = OBJECT_MAP.get(key); + if (instance == null) { + try { + instance = c.getDeclaredConstructor().newInstance(); + OBJECT_MAP.put(key, instance); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + throw new RuntimeException(e.getMessage(), e); } } } - return c.cast(instance); } } -- GitLab