How to ensure that the exception thrown by #Asynchronous method from EJB 3.1 methods are not silently eaten up by Future?
I know one can use Future.get method to retrieve exception but it will wait till the computation is done, a problem in case no exception occur and you have to wait till the computation is over.
(Update)
The scenario is fairly simple. A stateless EJB exposes its method with #Asynchronous annotation, primarily intended for #Local. The AS is JBoss. During computation, its possible that a RuntimeException occurs. Clients may or may not want to poll if the job is finished, but in all cases they should know if exception has occurred.
A workaround is possible to use some sort of callback, but I am interested if there is any out of box solution available.
Did you consider invoking Future#get(timeout, timeUnit) to return the control after the given time if no results are available (the computation is not finished)?
You can also invoke Future#isDone() prior to Future#get() to know if the processing is complete.
Either way, you still need to invoke Future#get(-) to get known what has happened and to be sure that the exception is not swallowed.
HTH.
There is a solution to your problem. The way countdownlatch is implemented is to notify the calling thread how many future tasks are done. here is an example hot to use countdownlatch. So implement a small synchronous class and add an instance to all callable objects while submitting. that shall work as callback.
If you have access to the configuration of your EJB container and you can set the executor, then you could Guava's addCallback method. This method requires a com.google.common.util.concurrent.ListenableFuture instead of an ordinary one. You will get this kind of future by setting the executor of your instance to a ListeningExecutorService. Guava provides a factory method for decorating each ExecutorService as ListeningExecutorService, so you are free to use whatever ExecutorService you had beforehand.
Related
In context of CompletableFuture I understand that thenApply(..) may use the current thread and may use the a pre-defined executor (e.g. ForkJoinPool) while thenApplyAsync(..) ensures that the pre-defined executor will be always used.
Far as I see the thenApplyAsync(..) seems be more "reliable" as it never blocks the current thread while thenApply(..) might be a surprise.
My question: Which example/scenario would be valid to use thenApply(..) rather than thenApplyAsync(..)?
Thanks, Christoph
Yes, thenApplyAsync would use some excecutor. This means that some Runnable object must be created and put in the executor's queue. If the function you want to execute after the complethion of this CompletableFuture is very simple, then invoking this method directly may be more efficient than creating envelope Runnable.
I (mostly) understand the three execution methods of CompletableFuture:
non-async (synchronous execution)
default async (asynchronous using the default executor)
custom async (asynchronous using a custom executor)
My question is: when should one favor the use of non-async methods?
What happens if you have a code block that invokes other methods that also return CompletableFutures? This might look cheap on the surface, but what happens if those methods also use non-async invocation? Doesn't this add up to one long non-async block that could get expensive?
Should one restrict the use of non-async execution to short, well-defined code-blocks that do not invoke other methods?
When should one favor the use of non-async methods?
The decision for continuations is no different than for the antecedent task itself. When do you choose to make an operation asynchronous (e.g., using a CompletableFuture) vs. writing purely synchronous code? The same guidance applies here.
If you are simply consuming the result or using the completion signal to kick off another asynchronous operation, then that itself is a cheap operation, and there is no reason not to use the synchronous completion methods.
On the other hand, if you are chaining together multiple long-running operations that would each be an async operation in their own right, then use the async completion methods.
If you're somewhere in between, trust your gut, or just go with the async completion methods. If you're not coordinating thousands of tasks, then you won't be adding a whole lot of overhead.
Should one restrict the use of non-async execution to short, well-defined code-blocks that do not invoke other methods?
I would use them for operations that are not long-running. You don't need to restrict their use to trivially short and simple callbacks. But I think you have the right idea.
If you're using CompletableFuture, then you have decided that at least some operations in your code base necessitate async execution, but presumably not all operations are async. How did you decide which should be async and which should not? If you apply that same analysis to continuations, I think you'll be fine.
What happens if you have a code block that invokes other methods that also return CompletableFutures? This might look cheap on the surface, but what happens if those methods also use non-async invocation? Doesn't this add up to one long non-async block that could get expensive?
Returning a CompletableFuture generally signifies that the underlying operation is scheduled to occur asynchronously, so that should not be a problem. In most cases, I would expect the flow to look something like this:
You synchronously call an async method returning a CompletableFuture. It schedules some async operation to eventually provide a result. Your call returns almost immediately, with no blocking.
Upon completion, one or more continuations may be invoked. Some of those may invoke additional async operations. Those will call into methods that will schedule additional async operations, but as before, they return almost immediately.
Go to (2), or finish.
I have a class A that implements Runnable interface, this class perform my batch job. Their is a controller class which is responsible for creating ExecutorService and submitting objects of Class A to ExecutorService instance in a for loop.
I want to terminated the execution of all task, if any task execution encounters exception as their is high probability that the exception will be caused in all task and I want the cause to be thrown to caller code.
How can I achieve this ?
As far as I can tell there is no magic on offer in the Jdk to mangage the cancellataion of the tasks (after a problem in another sibling thread). Looks like you need to keep track of the Future instances and manage the cancellation yourself.
Or find a library that has done the work for you. It might be worth investigating if Spring Batch supports this kind of case.
This question is Related to List returned from shutdownNow() can not be converted to submitted Runnable
Problem definition
I want to get runtime exception from Runnableand which I can get only using submit() call which returns me Future<?>.
If I use Submit I loose on the functionality which is provided by execute. As I will no longer able to use shutdownNow() to track not started threads.
So Is this true
If I want to catch runnable exception from my task I will never be able to use shutdownnow to find out not started task.
You can use execute() together with Future by using a custom subclass of FutureTask (which is a Runnable). for most Executors, calling submit() just wraps the Runnable/Callable with a FutureTask under the hood. In you custom subclass of FutureTask, keep a reference to the underlying Runnable/Callable and expose a method for returning it. then, when you call shutdownNow(), the returned Runnables should be instances of your custom FutureTask. (it's annoyting that you need to subclass FutureTask to be able to get at the underlying task, but that's the way it is).
I have a java application which calls a third party method, which can block indefinitely without throwing an exception.
Is it possible to wrap my method call in a timeout block (or thread, or other construct) such that I get back control after I assume the call is never returning?
The ThreadPoolExecutor should do what you need. Using the awaitTermination method:
Blocks until all tasks have completed execution after a shutdown
request, or the timeout occurs, or the current thread is interrupted,
whichever happens first.
all this multi threading is surely an answer but think if ur application is not a multi-threaded one, you can just store the timestamp of the moment you send the request and check it against the current timestamp. of course you will need a thread to keep track of the time. but all in all you can use that same thread for this purpose for as many functions calls you need. so dont go on implementing the runnable in ur classes. just make one tracker thread.