4

I have situation where I share singleton between my code which runs the embedded-server and my web-application. I have war with classes and deployment tool. When I printf instances I see:

abc.Abc@173a10f
abc.Abc@105738

So this is not really singleton. How this works?


My server Jetty start code:

public static void main(String[] args) throws Exception
{
    System.out.println(MySingleton.getInstance());
    // start Jetty here and deploy war with WebAppContext()
}

My ServletContextListener side code:

public class AppServletContextListener implements ServletContextListener{
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println(MySingleton.getInstance());
    }
}

My singleton:

public class MySingleton {
    private static MySingleton INSTANCE = new MySingleton();
    private MySingleton () {}
    public static MySingleton getInstance() {
        return INSTANCE;
    }
}

I forced exception inside constructor. It looks like I get two different.

java.lang.Exception
        at api.MySingleton.<init>(MySingleton.java:33)
        at api.MySingleton.<clinit>(MySingleton.java:22)
        at my.project.StartJetty.main(StartJetty.java:41)
java.lang.Exception
        at api.MySingleton.<init>(MySingleton.java:33)
        at api.MySingleton.<clinit>(MySingleton.java:22)
        at api.AppServletContextListener.contextInitialized(AppServletContextListener.java:25)
        at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:640)
        at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:229)
        at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1208)
        at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:586)
        at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:449)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
        at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:224)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
        at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
        at org.eclipse.jetty.server.Server.doStart(Server.java:258)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
        at my.project.StartJetty.main(StartJetty.java:66)
Charles
  • 50,943
  • 13
  • 104
  • 142
Knight of Ni
  • 1,780
  • 3
  • 20
  • 47
  • 2
    You haven't posted any code at all. – chrylis -cautiouslyoptimistic- Sep 11 '13 at 19:52
  • Singleton is pattern, assuming implemented properly you will have only one object in memory, but that doesn't mean you can't modify the state of the object. Whenever you change state of the object, depending on hashcode()/equals() implementation those numbers will change. – kosa Sep 11 '13 at 19:55
  • 1
    But is it possible that server runs the separate instances for the deployed page (restful code, servlets ...)? – Knight of Ni Sep 11 '13 at 19:58
  • Show us the code for `MySingleton.getInstance()`... – Sotirios Delimanolis Sep 11 '13 at 19:59
  • We still need to see your "MySingleton" code to help you and say that it is a well implemented Singleton. Once again, it is a design pattern, how are you implementing it? are you using annotations? are you using static get Instance that you wrote? – porfiriopartida Sep 11 '13 at 19:59
  • I can show a counter example of @Nambari 's claim. Great question. – Pete B. Sep 11 '13 at 20:02
  • nothing fancy inside singleton – Knight of Ni Sep 11 '13 at 20:02
  • 3
    Are both the `AppServletContextListener` and `main` method being executed in the same JVM? – Sotirios Delimanolis Sep 11 '13 at 20:02
  • @SotiriosDelimanolis: I hope. I have `AppServletContextListener` inside WAR registered with web.xml. – Knight of Ni Sep 11 '13 at 20:06
  • @PeteBelford: I know counter can be proven easy, that is why I have commented rather than answer to say there is possibility. – kosa Sep 11 '13 at 20:06
  • 2
    Jetty must be loading its own instance of `MyInstance` class with its own `ClassLoader`. – Sotirios Delimanolis Sep 11 '13 at 20:07
  • But is it something intentional? Like separation for different WAR/context/pages/web-apps. Maybe this is totally normal and I do something strange. – Knight of Ni Sep 11 '13 at 20:08
  • 2
    This might be a shot in the dark... but could your `MySingleton` class be getting loaded by more than one `ClassLoader`? If you've got two loaders in your JVM that don't talk to each other, it might be possible to have two different definitions of the same class floating around (for example, this happens all the time in the NetBeans RCP framework, so it isn't unprecedented). – CodeBlind Sep 11 '13 at 20:09
  • @BenLawry It seems that was the case. – Knight of Ni Sep 11 '13 at 20:42

3 Answers3

5

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Is this behavior for some purpose and should I expect this with other servers? – Knight of Ni Sep 11 '13 at 20:28
  • For servlet containers, there is no other way to do since you have to load `war`s. In other servers, you won't control the `main()` so you wouldn't have that worry. If you tried doing `MySingleton.getInstance()` twice in the listener, you'll get the same instance. Same if you did it in a servlet or other class in that context. – Sotirios Delimanolis Sep 11 '13 at 20:30
  • Exactly same observed. If I am using `MySingleton` in `ServletContextListener` and REST resources it is the same instance. – Knight of Ni Sep 11 '13 at 20:33
  • @flyer So classes loaded by Jetty display that singleton behavior you expect. You cannot have that expectation across multiple class loaders. – Sotirios Delimanolis Sep 11 '13 at 20:34
  • The `webAppContext.setParentLoaderPriority(true);` solved the problem. I see only one stack trace. That's awesome! Thanks. – Knight of Ni Sep 11 '13 at 20:41
2

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.

Kyle
  • 271
  • 1
  • 2
  • 10
2

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

fgb
  • 18,439
  • 2
  • 38
  • 52
Ranjith
  • 181
  • 2
  • 9