How do you handle async initialization of an object? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do you handle async initialization of an object? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Let’s say I have an object Foo which requires some asynchronous work, bar(), to be done before it is ready to be used. It feels like each solution I try, I run into an anti-pattern.

Solutions considered:

  • Keep an initialized variable in Foo. Call bar() in Foo’s constructor. When bar() completes, set initialized = true. My issue with this approach is that it introduces uninitialized and initialized states into the object, which in my understanding should be avoided.

  • Setup Foo in a parent and inject the data in via arguments. My problem with this approach is that it just pushes the issue farther up the stack; if this is done, now some other class is responsible for doing Foo‘s initial work.

What is common practice in a situation like this? Thanks!

Answer

How about a static factory method that returns a Future?

class Foo {
    private static final ExecutorService executor =
            Executors.newSingleThreadExecutor();
    
    public static Future<Foo> construct() {
        return executor.submit(() -> {
            bar();
            return new Foo();
        });
    }

    private Foo() {}
}
We are here to answer your question about How do you handle async initialization of an object? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji