what is lazy allocation?
Asked Answered
T

1

23

What does lazy allocation of objects mean and how is it useful?

Thermo answered 3/4, 2009 at 5:45 Comment(0)
I
22

Lazy allocation simply means not allocating a resource until it is actually needed. This is common with singleton objects, but strictly speaking, any time a resource is allocated as late as possible, you have an example of lazy allocation.

By delaying allocation of a resource until you actually need it, you can decrease startup time, and even eliminate the allocation entirely if you never actually use the object. In contrast, you could pre-allocate a resource you expect to need later, which can make later execution more efficient at the expense of startup time, and also avoids the possibility of the allocation failing later in program execution.

The following code provides an example of a lazily-allocated singleton:

public class Widget {
    private Widget singleton;

    public static Widget get() {
        if (singleton == null) {
            singleton = new Widget();
        }
        return singleton;
    }

    private Widget() {
        // ...
    }

    // ...
}

Do note that this code isn't threadsafe. In most cases, access to the get() method should be synchronized in some fashion.

A similar (and perhaps more general) concept is lazy initialization.

Intratelluric answered 3/4, 2009 at 6:16 Comment(2)
are the terms "late objects" and "lazy init" synonymous? As in the title of this text Java How to Program: Late Objects Version? I googled but couldn't find any references beyond that text.Palacios
@hydeph, it looks like Deitel has two versions of that book, one with "late objects", where the initial chapters are in procedural style (and introducing classes/objects later) and one with "early objects", where classes/objects are introduced immediately. They are using "late objects" and "early objects" to distinguish between these teaching styles. It doesn't have any relationship to lazy initialization.Intratelluric

© 2022 - 2024 — McMap. All rights reserved.