Skip to content

Instantly share code, notes, and snippets.

@nipafx
Last active May 18, 2022 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nipafx/77dc797e39584b9c8191c71ee7ff3a24 to your computer and use it in GitHub Desktop.
Save nipafx/77dc797e39584b9c8191c71ee7ff3a24 to your computer and use it in GitHub Desktop.
Non-asyncronous EA Async example
// Two examples [1, 2] from EA Async written without async/await or
// (Completable)Futures as straight-forward blocking code. If the
// callers want to do something concurrently to `Store::buyItem`,
// they just put that call into a new virtual threads.
public class Store {
private final Bank bank = new Bank();
private final Inventory inventory = new Inventory();
public boolean buyItem_v1(String itemTypeId, int cost)
throws InterruptedException {
boolean decrementSuccessful = bank.decrement(cost);
if (!decrementSuccessful)
return false;
inventory.give(itemTypeId);
return true;
}
public boolean buyItem_v2(String itemTypeId, int cost)
throws InterruptedException, AppException {
boolean decrementSuccessful = bank.decrement(cost);
if (!decrementSuccessful)
return false;
try {
inventory.give(itemTypeId);
return true;
} catch (InterruptedException ex) {
throw ex;
} catch (Exception ex) {
bank.refund(cost);
throw new AppException(ex);
}
}
}
class StoreUser {
private final Store store = new Store();
public void useStore(String itemTypeId, int cost)
throws InterruptedException {
try (var scope = new StructuredTaskScope<Boolean>()) {
scope.fork(() -> store.buyItem_v2(itemTypeId, cost));
scope.fork(() -> reorderItem(itemTypeId));
scope.join();
// maybe handle error
}
}
private boolean reorderItem(String itemTypeId) {
return true;
}
}
class Bank {
public boolean decrement(int cost)
throws InterruptedException {
return true;
}
public boolean refund(int cost)
throws InterruptedException {
return true;
}
}
class Inventory {
public String give(String itemTypeId)
throws InterruptedException {
return "";
}
}
class AppException extends Exception {
public AppException(Throwable cause) {
super(cause);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment