Pass transaction context under completableFutures

Viewed 101

I have a code that basically does something like this:

private void example() {
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  def.setName("name");
  TransactionStatus status = txManager.getTransaction(def);
  try {

    List<LinkedHashMap<Integer, String>> itemsList = new ArrayList<>();
    //imagine this list has 10 items.

    List<CompletableFuture<List<String>>>  completableFutures;

    completableFutures=itemsList.stream().map( chunkList -> {
      return CompletableFuture.completedFuture(chunkList)
        .thenApplyAsync(chunkListVar -> {
          List<String> subList = new ArrayList<>();
          subList.add( chunkListVar + " World");
          //here inside have some Business logic with some inserts and/or updates
          return subList;
        }, executorService);
      }).collect(Collectors.toList());

    txManager.commit(status);
  } catch (Exception ex) {
    txManager.rollback(status);
  }

}

So what is happening is that I'm forcing a scenario when it throws a exception to see rollback in action, but what I'm getting is every insert or update inside threads are been executed and committed on time, because it doesn't have the transaction context.

How can I have all queries inside the transaction created outside so, if anything goes wrong, I could roll back all queries?

0 Answers
Related