user771
user771

Reputation: 49

How to call multiple methods asynchrounosly with different implementation

I am trying to call one method 12 times asynchronously. But before the call I am setting something different for each method call. How can I do this in a more elegant way.

I am using spring as well.

I am aware of @async but how can I change the body 12 times ?

Callable<Object> task4 = () -> {

        CallContextHolder.setContext(callContext);
        try {

            Object m = dbQuery(userId);
            if (m == null){
                throw new RuntimeException();
            }
            return m;
        }
        catch (Exception e) {
            throw new IllegalStateException("task interrupted", e);
        }
    };
    Callable<Object> task5 = () -> {

        CallContextHolder.setContext(callContext); //here is the difference in every task
        try {

            Object m = dbQuery(userId);
            if (m == null){
                throw new RuntimeException();
            }
            return m;
        }
        catch (Exception e) {
            throw new IllegalStateException("task interrupted", e);
        }

Upvotes: 0

Views: 88

Answers (1)

Ivan
Ivan

Reputation: 8758

You can use something like the following method

public Callable<Object> getCallable(CallContext context, String userId) { //replace types fro parameters to appropriate
    return () -> {
      CallContextHolder.setContext(callContext);
      try {
        Object m = dbQuery(userId);
        if (m == null){
            throw new RuntimeException();
        }
        return m;
      }
      catch (Exception e) {
        throw new IllegalStateException("task interrupted", e);
      }
   };
}

And use it like this

Callable<Object> call1 = getCallable(callContext, userId);
Callable<Object> call2 = getCallable(callContext, userId);

You can try to use some type of loop to generate those callables and store them in a list.

Upvotes: 1

Related Questions