Home  >  Q&A  >  body text

java - 关于单例模式多ClassLoader问题解决方法的疑问

在这里查看单例模式的讲解:http://cantellow.iteye.com/bl... 后面总结中有下面一个问题以及解决的方案,但我不太懂是什么意思,麻烦大神给解答下,谢谢~

问题:

1.如果单例由不同的类装载器装入,那便有可能存在多个单例类的实例。假定不是远端存取,例如一些servlet容器对每个servlet使用完全不同的类装载器,这样的话如果有两个servlet访问一个单例类,它们就都会有各自的实例。

private static Class getClass(String classname) throws ClassNotFoundException {     
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();     
      
      if(classLoader == null)     
         classLoader = Singleton.class.getClassLoader();     
      
      return (classLoader.loadClass(classname));     
   }     
}  
阿神阿神2763 days ago384

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:46:45

    For any class, the class loader that loads it and the class itself need to establish its uniqueness in the Java virtual machine. So if you use different class loaders to load multiple classes, you can also have multiple instances. These instances operate the same but are instances of different classes to the JVM. I have written an article explaining this issue before. You can refer to it. I hope it will be helpful to you.

    https://segmentfault.com/a/11...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:46:45

    I don’t understand what part you don’t understand. I can only speculate that you may need to learn the class loading process, the parent delegation mechanism of the class loader

    reply
    0
  • Cancelreply