Over a million developers have joined DZone.

Always Start With Eager Initialization

Lazy initialization should always be a last ditch resource; it's harder to comprehend and write with relatively little benefit

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

The discussion surrounding eager and lazy initialization tends to revolve around Singletons although not exclusively. Should an object be created when it’s requested or in advance? For me the answer is a no brainer: Eager instantiation is just better.

I’ll caveat up front; there are exceptions. But unless it’s a very exceptional case you should always favour eager instantiation of your objects.

The old discussion was simple. Lazy initialization is useful for “expensive” objects or objects which may never get executed. Let’s look at this code sample of a (non thread safe) Singleton:

public class ExpensiveObject {
    public static ExpensiveObject instance = null;

    private ExpensiveObject(){};

    public static ExpensiveObject instance(){
        if(instance == null){
            instance = new ExpensiveObject();
        }
        return instance;
    }
}

Our ExpensiveObject doesn’t get built until it’s requested. If it’s never requested then we’ve potentially dodged a bullet! But in reality most use cases where I’ve seen this sort of code it will always be executed. As a result we’ve had to put a whole bunch of extra logic in that needs to be tested and exposes us to a bunch of threading issues. I have to put a synchronized block in for the creation and access of the object. This potentially impacts the performance of the application and it certainly impacts the legibility of the code.

public class ExpensiveObject {
    public static volatile ExpensiveObject instance = null;

    private ExpensiveObject(){};

    public static ExpensiveObject instance(){
        if(instance == null){
            synchronized (this){
                if(instance== null)
                    instance = new ExpensiveObject();
            }
        }
        return instance;
    }
}

This code is messy and takes time to reason about, particularly if you’re not familiar with the double checked locking patter in Java. It is necessary to declare the field volatile to ensure thread safety which results in a performance impediment. There is one more option for a thread safe lazy initialisation, the initialisation-on-demand idiom:

public class ExpensiveObject {
    private static class Holder{
        public static ExpensiveObject instance = new ExpensiveObject();
    }

    private ExpensiveObject(){};

    public static ExpensiveObject instance(){
        return Holder.instance;
    }
}

This code is certainly an improvement- performance wise there’s only a single syncronized call (implicit on the creation of the field). However when writing code the clarity and readability is of upmost importance. This code is still complicated and assumes the reader understands how the class loader works so that this guarantees thread safety. Although the code is logically sound, it is bad code because it is hard to reason about.

Writing multithreaded code is difficult. Anyone who says otherwise is lying. It’s hard to reason about, write and then understand. If we can avoid threaded code then we should.

Let’s look at an example with eager instantiation:

public static final ExpensiveObject instance = new ExpensiveObject();

    private ExpensiveObject(){};

    public static ExpensiveObject instance(){
        return instance;
    }

Not only is this code cleaner and easier to understand, it’s also safer and more performant. It also means we can declare the field final!

But what of the objects “expensiveness”? This is a good question which most people rarely look into. Let’s look at some definitions of expensive:

  • Time — the object takes a large amount of time to create. In this scenario we should definitely favour eager initialisation. It’s better to take the time hit during application startup than impact user performance.

  • Memory/Object Size — Perhaps your Object is a whopping monster that might take up a huge chunk of your memory. I’d be genuinely interested to know what optional functionality requires such a gigantic Object outside of something like a UI. If it’s likely to get used on most application usages, then just create it up front. Again, the cleanliness of the code is more valuable. Furthermore RAM is really cheap these days, and whilst I’m not advocating being careless with memory I believe that you are unlikely to be operating in an environment where the creation of your object could be the difference between a stable application and an OutOfMemoryException.

  • Connections — A genuine exception. Things like Database Connections can genuinely be expensive in terms of memory and Thread usage. Again, I feel it’s unlikely an application will have something like this being so optional and rarely called that it justifies lazy instantiation, but your mileage may vary.

When creating our code the priority should be clear understanding for anyone reading our code later (including ourselves) and simple code that is easy to test and reason about. Your default position should always be to eagerly initialize. Lazy initialization off the bat is premature optimization; measure your application, and if there is a genuine problem being caused then look to change to lazy. Chances are this will be very rare.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java ,singleton ,singleton design pattern

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}