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 inFoo
. Callbar()
in Foo's constructor. Whenbar()
completes, setinitialized = 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 doingFoo
'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() {}
}