DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Docker Image Building Best Practices
  • Introduction Garbage Collection Java
  • Dynatrace Perform: Day Two
  • Ultimate Guide to FaceIO

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • A Complete Guide to Modern AI Developer Tools
  • Solid Testing Strategies for Salesforce Releases
  • Internal Developer Portals: Modern DevOps's Missing Piece
  1. DZone
  2. Coding
  3. Languages
  4. Always Start With Eager Initialization

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

By 
Sam Atkinson user avatar
Sam Atkinson
·
Mar. 29, 16 · Opinion
Likes (13)
Comment
Save
Tweet
Share
28.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Object (computer science) application IT Lazy initialization

Opinions expressed by DZone contributors are their own.

Related

  • Docker Image Building Best Practices
  • Introduction Garbage Collection Java
  • Dynatrace Perform: Day Two
  • Ultimate Guide to FaceIO

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!