First of all, I've decided to make my class blocking (to make it easier for the consumer to use - but maybe more tedious for me to write). As opposed to having the consumer define asynchronous callbacks. Is this a good design pattern? This way, a user can get expected behaviour, but implement their own multi-threading if they're dissatisfied with how long the thread's blocked for.
I've got a constructor that sets a final field in a class, based on the result of an async callback:
class Example {
private final int x;
Example(){
asyncFunc(/* callback */ result -> x = result)
}
}
This doesn't work, so I've used atomic references, and implemented a blocking loop, until the result it returned, like so:
class Example {
private final int x;
Example(){
x = waitAsyncFunc();
}
private int waitAsyncFunc(){
AtomicBoolean finished = new AtomicBoolean(false);
AtomicReference<byte[]> result = new AtomicReference<>();
asyncFunc(result -> {
result .set(res);
finished.set(true);
});
while (!finished.get()) { /* No op */ }
return result.get();
}
}
Is this a good way to block / retrieve the result?