dev hedgehog
dev hedgehog

Reputation: 8791

Catch Return Value of An Interceptor

I would like to retrieve the return value of this interceptor:

https://arjan-tijms.omnifaces.org/2012/01/cdi-based-asynchronous-alternative.html

@Interceptor
@Asynchronous
@Priority(PLATFORM_BEFORE)
public class AsynchronousInterceptor implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @Resource
    private ManagedExecutorService managedExecutorService;
    
    private static final ThreadLocal<Boolean> asyncInvocation = new ThreadLocal<Boolean>();

    @AroundInvoke
    public synchronized Object submitAsync(InvocationContext ctx) throws Exception {
        
        if (TRUE.equals(asyncInvocation.get())) {
            return ctx.proceed();
        }
        
        return new FutureDelegator(managedExecutorService.submit( ()-> { 
            try {
                asyncInvocation.set(TRUE);
                return ctx.proceed();
            } finally {
                 asyncInvocation.remove();
            }
        }));
  
    }
}

here is a CdiBean of mine profiting from AsynchronousInterceptor by letting data be loaded async..

public class SomeCDI {
   @Asynchronous
   public void loadDataAsync() {....}
}

this is how I use the cdi bean later in code:

@Inject
SomeCDI dataLoader;

dataLoader.loadDataAsync(); // the loading starts async but I never find out when is the Future class done???

so my question is how to retrieve return value (in my example from FutureDelegator)???

Upvotes: 0

Views: 244

Answers (1)

Paulo Ara&#250;jo
Paulo Ara&#250;jo

Reputation: 569

You won't. Asynchronous invocations on EJB and in the model suggested by Tijms are "fire and forget": you invoke them and let them do their job. Eventually, you can make the async method fire some event when it ends to "return" the result, observing this event to give user some response (websockets, maybe?).

Ideally, the asynchronous method should be void and do some callback lift.

Note that CDI 2.0 event model has the fireAsync method, which should be used instead of your own implementation, as it already have the proper contexts and can be enriched by transaction markers and custom options (when using NotificationOptions method signature).

Upvotes: 1

Related Questions