Executor Service issue with Submit and ShutdownNow with RunnableException - java

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).

Related

When to use CompletableFuture#thenApply(..) over thenApplyAsync(..)?

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.

Customized ThreadPoolExecutor to execute some tasks concurrently and some in queue

I am creating an MVP application with Java Swing. I need to execute various Tasks that are instances of a Taskclass, I created extending SwingWorker class!
I came across Executors class but none of the provided executors seem to fulfil my needs.
I want to execute some of my Task instances concurrently and some of my Task instances in queue. Also, I want a method invocation when all tasks have been completed. Like, done method in SwingWorker class!
abstract class CustomExecutor extends ThreadPoolExecutor {
CustomExecutor(Collection<Task> synchronousTasks, Collection<Task> asynchronousTasks) {
// .........
}
// To be called when all tasks have been executed successfully!
abstract void done();
}
I have not used ExecutorService or ThreadPoolExecutor before and unable to come up with any solution!
Let's briefly compare the two solutions you mentioned - SwingWorker and Executors framework. The general idea behind the two solutions is similar, but depending on the use case one can be better over the other.
SwingWorker
executes asynchronously the logic implemented in the doInBackground method.
you need to subclass SwingWorker to implement the logic
there are some useful methods to integrate with Swing and update the UI in the Event Dispatch Thread - publish(), process(), done(), get/setProgress() and some property change listener support methods.
a single instance of SwingWorker corresponds to a single task
when you invoke SwingWorker.execute(), internally the worker instance submits itself as a task (Callable) to an ExecutorService (to be precise - a ThreadPoolExecutor) so that the logic implemented in the doInBackground method is executed asynchronously in a separate thread
there is a default configuration of the ThreadPoolExecutor used by all the SwingWorker objects you ever create, hidden in the SwingWorker class. If you want to provide your own ExecutorService for executing the SwingWorkers, you can do so by setting sun.awt.AppContext.getAppContext().put(SwingWorker.class, yourOwnExecutorService). However, as I said, you can have only one global ExecutorService for all the SwingWorkers in your application.
to summarize: SwingWorker hides the concurrency details from you, but exposes API to communicate with the Swing UI. Use SwingWorker if your tasks first need to do some computation in the background and then update the UI.
More about Concurrency in Swing
Executors framework
You are in full control of the ExecutorService configuration - there are utility methods in the Executors class to create some common configurations or you can instantiate a ThreadPoolExecutor yourself.
The framework is generic - it accepts any Runnable/Callable tasks, which may perform any logic. There is no special support for Swing.
You need to shutdown the ExecutorService yourself.
More about Executors Framework
If I understand your requirement correctly, you might prefer to use ExecutorService rather than SwingWorker, so that you have more control over the concurrency. Submit the tasks that you want to be queued (ie. executed sequentially) to an executor created with Executors#newSingleThreadExecutor(). For the tasks that you want to be executed concurrently, use a different ExecutorService - created with Executors#newCachedThreadPool(), Executors#newFixedThreadPool(int) or a custom ThreadPoolExecutor. See Javadocs to check which fits your needs best.
You can use ExecutorService#invokeAll() to submit multiple tasks at once and to block until they are done or you can call ExecutorService#submit() in a loop to submit them one by one without blocking and at a later moment call Future.get() on the Future obtained from submit() to block until the execution is done.
Once you have called get() on all futures - both those corresponding to synchronousTasks and asynchronousTasks, you know that all are done and you can call your done() method.
If you want to learn even more, I recommend reading the Javadocs and the source code of SwingWorker, Executor and ExecutorService classes.

ExecutorService-like class where user controls when Callables are called

I was using an ExecutorService to schedule tasks to be executed in future. After seeing some "odd" behavior where my Callable was getting executed before I called get() on the Future object returned by submitting my Callable to the ExecutorService pool, I read some documentation and found that the submitted task will get executed between the time it gets submitted or at the latest when get() is called on the Future object.
My question - is there any class that would allow Callables to be submitted to it and ONLY executed when get() is called on it? At this point, it seems like just managing the Callables myself and calling call() on them myself when I am ready for them to be executed seems like it'd accomplish what I want, but I wanted to make sure there was no service already implemented that accomplished this.
In short, is there any alternative to ExecutorService that lets me control when Callables submitted to it are called? Note - the time in the future that I want them called is variable and not determined as I may decide not to call them so a ScheduledExecutorService pool won't work here.
Thanks much!
Sounds like you really want to use a Queue<Callable> instead and just poll the queue for tasks.
That way you can submit as many tasks as you like and execute them at your will - one by one.

Queueing Runnable objects for execution in one thread

Is this possible to queue multiple Runnable objects to wait for execution in one thread? How it can be done without using ExecutorService? What's gonna happen if one of those Runnable objects threw unchecked exception, does it stop executing thread?
Is this possible to queue multiple Runnable objects to wait for execution in one thread?
Use an ExecutorService.
How it can be done without using ExecutorService?
Use a BlockingQUeue and Thread.
What's gonna happen if one of those Runnable objects threw unchecked exception, does it stop executing thread?
That's up to you since you have to writ this yourself.
For an ExecutorService, the Throwable thrown is added to the Future object for you to check. Its very easy to forget to do this, in which case you need to add a try/catch block to you Runnable.
Is there a specific reason for not using an ExecutorService? It provides an implementation working in one Thread: Executors.newSingleThreadExecutor()
It is possible.
Open a thread the listens to a queue, each time it sees a item, it deques and runs it.
You can wrap the execution of the task in a try catch block, thus allowing the worker thread to continue working even if one of the tasks threw an exception.
Having said that- the above is exactly what a ThreadPoolExecuter does, so why wouldn't you want to use it? (Homework?)

Future<V> and Exception

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.

Categories