我最近了解到一个java程序可以有多个类加载器。我发现一些 StackOverflow 帖子解释了如何创建单例对象。
常见的方法是这样的:
if (instance == null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = Singleton.class.getClassLoader();
}
Class<?> sclass = (classLoader.loadClass(Singleton.class.getCanonicalName()));
}
我不太明白这是如何摆脱多个类加载器的问题的。如果您有多个 ClassLoader,则当每个 ClassLoader 尝试加载该类时,该实例将为 null。这不是正确的吗?如果我能得到关于其工作原理的简短解释,我会发现它会很有帮助。
此外,我们什么时候能够检索实际的 Singleton 实例?我可以执行类似 instance = (Singleton) sclass.newInstance();
的操作,但这将为每个 ClassLoader
创建一个新实例。
最佳答案
how this gets rid of the issue of multiple classloaders.
我不明白你指的是哪个问题,但它并没有消除任何问题。
the instance will be null when each of them tries to load the class.
实例不会为空。
we able to retrieve the actual Singleton instance?
当线程拥有所需的ClassLoader时,您可以使用任一方法获取SIngleton实例。
Singleton s = Singleton.INSTANCE;
或
Singleton s = Singleton.getInstance();
取决于您通常如何访问单例。如果您需要在另一个类加载器中使用单例,则必须执行相同的操作,除非通过反射。
关于java - 多个类加载器和单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276295/