Singleton is not really a singleton

不打扰是莪最后的温柔 提交于 2019-12-04 10:10:15

Have a look at some Jetty documentation. You can play around with class loading configurations.

If set to true, then Jetty uses normal JavaSE classloading priority, and gives priority to the parent/system classloader. This avoids the issues of multiple versions of a class within a webapp, but the version the parent/system loader provides must be the right version for all webapps you configure in this way.

This is exactly the situation you are describing. One MySingleton instance is being loaded by the main Java program and another is being loaded by Jetty's class loader.

Printing a stack trace in the constructor should give you the information you need to find out where it is being instantiated and what order. The Singleton pattern is a dangerous thing, usually better to do it a different way.

Ranjith

Your ServletContextListener and main classes are loaded by different class loaders. Whenever a class gets loaded, its static block will be executed. so you will get two instances...

If you want to make sure the same classloader loads your singleton, you must specify the classloader yourself.

check this link for more details http://www.javaworld.com/article/2073352/core-java/simply-singleton.html?page=2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!