Learn to Stop Worrying and Love the Singleton

Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes.

Dependency injection and early validation is crucial for an enterprise application, and Spring is a boon in this regard. But do not fool yourself, Spring is good, but it is not a universal cure. Especially not in mobile space where startup times, low memory consumption, and avoiding interfaces are virtues.

The bottleneck in an enterprise application is most probably the database, spending a few extra milliseconds here and there seldom matters. On much less performant mobile device those clock cycles are not only time the user has to spend waiting, it will drain the battery. A simple thing as using an interface instead of an abstract superclass will perform at least twice as slow. Even passing an extra argument in the constructors a few nestings deep will have an impact.

Lazy Singeltons by Choice

Class loading in Java is lazy, the Java VM will not load classes until they are referenced. Odds are that the user will not trigger a full coverage of all classes in your app for a short time running mobile app. If the user just checks for incoming messages and quits, then every class involved in composing messages do not need to be loaded. Early dependency injection breaks this, as all classes will be referenced at startup. Most components will be initialized in vain, as they are never actually used.

So what we should do in mobile application is to work more like the Java VM, and less like Spring. If possible do not create a component until it is requested. The best way to do this is using a singleton pattern. Not a normal enforced singleton pattern, but rather a singleton by choice. Let the constructor be public, trust your users, and name the getter getSharedFoo(), not getInstance(). Let me show you using a example of an URL cache component:

Using this shared URL cache component from our imaginary HTTP provider would then be super easy, but not mandatory:

The big win here is that if the code path of this run of the application never tries to open an input stream then the URL cache never has to be created. Saving several hundred milliseconds of reading cache indexes, validation, etc.

But What About Testing?

Are not singletons bad for unit tests and mocking components? They used to be. These days we have PowerMock, you really should use it. Turns out that not even PowerMock is really required, if we just change our singleton pattern very slightly, and allows the outside to set the shared component as well:

This small addition allows us for setup up our own mock cache in the setup of our unit tests. With something as simple as this:

It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.

Take Aways

Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.

Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.

Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.

This Post Has 8 Comments

  1. I agree with you, singletons can be quite useful, especially when your application is running in a constrained environment such as an embedded device. I have some comments:

    First, if your singleton is a part of an API, you should consider making the default constructor private. If you don’t, other developers can create their own instances of the class and then it’s not a singleton anymore…

    Secondly, if you are really worried about performance, you can get rid of the overhead associated with the synchronization each time the shared resource is accessed by using the initialization on demand holder idiom:

    Lastly, the single-element enum pattern suggested by Joshua Bloch in his book Effective Java (2nd Edition) is probably the most concise singleton implementation that you will find. One drawback is that the enum keyword requires Java 5, which rules out Java ME developers, but Android developers may find it quite neat:

    public enum Singleton {
    1. Making the constructor private, or marking classes as final is actually something I loathe. It makes it hard for clients of my code to extend and adapt my code if/when needed. This is why I like to use the term singleton by choice, as I see it currently only one instance is needed, and therefor quick access to and creation of this single instance when it is needed is important.

      Maybe I should have been more clear in my text, but notice that I say URLCache.getSharedInstance(), not URLCache.getInstance(). This I do to show that it is the single instance that should be safe to use by component that needs it, but it is not necessarily the only instance available.

      I would also like to point out the importance of URLCache.setSharedInstance(). In nine out of ten this method will never be called, since the default URL cache has been chosen to cover what most clients need. But then once in a while, for example with a Java ME VM on a Windows Mobile device a tweaked implementation is needed.

      Now if I had made the constructor private it would be impossible to extend the URLCache class with a special subclass for Windows Mobile as easily as this:

  2. I really like this approach and I’ll probably start approaching this pattern in my PHP applications.

    Do you have a reference for this pattern, or this something you invented?

    1. Sorry for late reply, comment notifications seems to be down.

      No this is not a pattern I have invented. It has been the common practice in NeXTStep since 1989, and thus it’s descendants Cocoa for Mac OS X and Cocoa Touch for iPhone OS.

      I have just brought the practice back into the Java world, where the fear of singletons is prevalent.

  3. Wouldn’t it make things more difficult for Android developers. You’re basically creating a class with static getters and setters.
    How would you stub and test other parts of code that it is being called without calling this fragment.
    someMethod() {

    How do you test that getSharedUrlCache has been called without calling the method (Stubbing)

  4. are you serious?

    With this “approach”:

    1) You’re making public a property that is private(bye bye encapsulation)
    2) Every time setter is called, a new instance(used or not) is being created to be sent as parameter (bye bye singleton pattern).

    So, basically you did nothing.

    Is like the magic “approach” of making the variable public.

  5. What if we use “private” in “setSharedURLCache” and Java reflection during JUnit tests?
    * Cons: It only works in secure environments, like JUnit.
    * Pros: You can still mock by setting. Even if it breaks singleton pattern and encapsulation during JUnit.

    public void fixture() {

    URLCache mockURLCache = mock(URLCache.class);
    // More code to mock this object.

    Method method;
    String expected = “setSharedURLCache”;

    try {
    method = URLCache.class.getDeclaredMethod(expected, URLCache.class);


    method.invoke(method, mockURLCache);


    } catch (NoSuchMethodException |
    InvocationTargetException |
    IllegalAccessException e) {


  6. How to deal with singleton – refactor it to non-singleton…

Leave a Reply

Close Menu