Home > Blockchain >  How do you handle async initialization of an object?
How do you handle async initialization of an object?

Time:12-29

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!

CodePudding user response:

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() {}
}
  • Related