colioli
colioli

Reputation: 63

How do you handle async initialization of an object?

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:

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

Upvotes: 0

Views: 202

Answers (1)

shmosel
shmosel

Reputation: 50716

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

Upvotes: 4

Related Questions