How to get an Exception from Task runing in ExecutorService? - java

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.

Related

Java Thread.suspend() gracefully

EDIT: Updated question to explain exactly what I need.
So I am attaching a javaagent to a process using
VirtualMachine vm = VirtualMachine.attach(processPid);
vm.loadAgent(jarPath);
Now my agent runs on a separate thread. Now what I need to do is load all my transformers before any classes load. There is a thread in the attached process that loads all the classes. I want to be able to suspend this thread at the right time (without causing deadlocks) to wait for all my initialization (including a download) AND THEN register my transformers. It is important that the transformers are registred before anything else than the main class loads so I can modify the classes however I want.
I am currently just getting the thread by it's name and calling suspend() on it. But that causes deadlocks. Is there any way for me to make that thread wait on me?
Things I've tried:
Transforming the main class instantly to add a Thread.sleep(), didn't work because my agent loads after the main class
Using Thread.suspend which causes deadlocks.
What does "a thread that I do not have control over" mean? If your code calls t.suspend(), then that is a kind of control. Are you trying to tell us that the thread executes code for which you can not obtain the source?
What does "gracefully suspend" mean? If your program called t.suspend(), would it be possible for your program to decide whether it had suspended the thread at a "good" time?
You say that you want to suspend the thread while your program does something else. Can you explain in more detail what the thread does, and what you want your program to do while the thread is suspended, and why you can't allow both things to happen at the same time?
If your program could tell the difference between a good time and a bad time, and it picked a bad time, then would it make sense for the program to resume the thread and then try again later?

Is Thread to be favoured over Executor here?

As far as I understand Executors help handling the execution of runnables. E.g. I would choose using an executor when I have several worker threads that do their job and then terminate.
The executor would handle the creation and the termination of the Threads needed to execute the worker runnables.
However now I am facing another situation. A fixed number of classes/objects shall encapsulate their own thread. So the thread is started at the creation of those objects and the Thread shall continue running for the whole life time of these objects.
The few objects in turn are created at the start of the programm and exist for the whole run time.
I guess Threads are preferable over Executors in this situation, however when I read the internet everybody seems to suggest using Executors over Threads in any possible situation.
Can somebody please tell me if I want to choose Executors or Threads here and why?
Thanks
You're somewhat mixing things. Executor is just an interface. Thread is a core class. There's nothing which directly implies that Executor implementations execute tasks in separate threads.
Read the first few lines of the JavaDoc.
Executor
So if you want full control, just use Thread and do things on your own.
Without knowing more about the context, it's hard to give a good answer, but generally speaking I'd say that the situations that calls for using Thread are pretty few and far between. If you start trying to synchronize your program "manually" using synchronized I bet things will get out of hand quickly. (Not to mention how hard it will be to debug the code.)
Last time I used a thread was when I wanted to record some audio in the background. It was a "start"/"stop" kind of thing, and not "task oriented". (I tried long and hard to try to find an audio library that would encapsulate that for me but failed.)
If you choose to go for a thread-solution, I suggest you try to limit the scope of the thread to only execute within the associated object. This will to an as large extent as possible avoid forcing you to think about happens-before relations, thread-safe publishing of values etc throughout the code.
ExecutorService can have thread pool
It optimizes performance, because creating a Thread is expensive.
ExecutorService has life cycle control
shutdown(), shutdownNow() etc are provided.
ExecutorService is flexible
You could invoke variety of behaviors: customize ThreadFactory, set thread pool size, delay behavior ScheduledThreadPoolExecutor etc...

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.

what is the relationship of thread and task?

I know that Thread and Task are in different abstraction-level.But anyway,I'm still confused that what's the relationship of them.And,by the way,I think that the Task tells how to do a job and the Thread actually excute the job according to a Task instance.Is my understanding correct?thank u^
I assume by Task you mean Runnable and Callable. The relationship is simple:
Thread might be used to execute multiple tasks
might - because you don't need a separate thread to execute tasks (well, technically, everything runs inside a thread - you don't need a separate one)
multiple - thread can be reused; it can run multiple tasks from a collection like queue
Typically one thread executes one Runnable passed to Thread constructor or multiple Callables passed to ExecutorService (wrapping thread pool in most cases).
If by Task you mean something like this, then the difference is that the task is used to run some thread-like code execution, but has additional properties, such as when to run it, how many times, and the option to cancel its execution, whereas a thread will just go ahead and run once immediately.
A task is rather abstract it can be implemented as a process or a thread.
Your understanding is correct.
We can do the analogy with workflow patterns where tasks are something that needs to be done in a process and threads are resources used to process or execute them.

Categories