I'm using ExecutorService, Future and Callable to do parallel processing. Though the Callable's exception can be caught when invoking Future#get, how to catch all the exceptions thrown by all callables and then throw a huge, compound exception, like:
ExecutorService service = Executors.newFixedThreadPool(5);
List<Future<Void>> futures = new ArrayList<Future<Void>>();
futures.add(service.submit(new TaskA());
futures.add(service.submit(new TaskB());
for (Future<Void> future : futures) {
try {
future.get();
} catch (Exception e) {
// ???
}
}
// throw the big exception here
service.shutdown();
If you want to associate multiple exceptions with a single throw, use addSuppressed on your outermost exception.
It won't help you much on the catch side, but comprehensive error handling is never easy, especially after joining multiple threads of control.
Maybe I'm missing something, but
public class CompositeException extends Exception {
private List<Exception> exceptions = new ArrayList<Exception>();
public List<Exception> getExceptions() {
return exceptions;
}
}
Instantiate one of these puppies and load it up with all the exceptions before throwing it.
Related
I am using ExecutorService and Callable in Java. The class implementing Callable does some IO work on the filesystem. How do I stop the execution of a callable and exit from it, if an Exception occurs?
This is an example class implementing Callable that has two methods, foo1() and foo2()
public class MyCallable<Object> implements Callable<Object> {
public Object call() throws IOException, SQLException {
// method 1 , could throw IOException
foo1();
// method 2 , could throw SQLException
foo2();
return null;
}
}
This is the example execution service class. It can deal with exceptions occurred during the parallel processing through the futures object.
public class MyExecutorService {
ExecutorService listProcessor;
listProcessor = Executors.newFixedThreadPool(2);
List<Callable<Object>> callableTodo = new ArrayList<Callable<Object>>();
// add the callables to the todo list
callableTodo.add(new MyCallable<Object>());
callableTodo.add(new MyCallable<Object>());
// start the threads
List<Future<Object>> futures = listProcessor.invokeAll(callableTodo);
listProcessor.shutdown();
listProcessor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
// futures now holds possible exceptions
for (Future<Object> future : futures) {
try {
future.get();
} catch (ExecutionException e) {
// process the exception
}
}
}
But I would like to immediately let the MyCallable stop if for example a IOException occurs in foo1(), and not let it continue with foo2();
EDIT: Also, if an unchecked exception such as a RuntimeException occurs in foo1(), MyCallable also needs to stop.
The signature of Callable<V>'s call method is
V call() throws Exception
and its description is
Computes a result, or throws an exception if unable to do so.
In other words, just don't catch the IOException. If you don't catch it, then execution stops and the exception is passed up a level.
Note: this only works for non-RuntimeExceptions if the method is marked as throwing an exception type, which call is marked as doing because it's declared as throws Exception.
As you're already aware, Future's .get method will throw an ExecutionException if the Callable throws an exception.
I want to call a method in java which blocks for some reason. I want to wait for the method for X minutes and then I want to stop that method.
I have read one solution here on StackOverflow which gave me a first quick start. I am writing that here :-
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}
But now my problem is, my function can throw some Exception which I have to catch and do some task accordingly. So if in code the function blockingMethod() thorws some exception how do I catch them in Outer class ?
You have everything set up to do that in the code you provide. Just replace
// handle other exceptions
with your exception handling.
If you need to get your specific Exception you get it with:
Throwable t = e.getCause();
And to differentiate between your Exceptions you can do like this:
if (t instanceof MyException1) {
...
} else if (t instanceof MyException2) {
...
...
In cause of ExecutionException instance, I suppose.
In the ExecutionException catch block: e.getCause()
https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause
thread.sleep(x millisecods) will stop the thread for x milliseconds, then it will resume. The other way to do it is to call thread.wait(x) (with a timeout value for x) and then call thread.notify() to "wake" the sleeping thread.
I'm completely new to this code and begun to questions the design choices of the original developers.
I have a multi-threaded Java application that processes a number of tasks. My job is to fix the exception handling in the code so that when a RuntimeException occurs (iBatis and/or NullPointerException) the rest of the tasks are executed instead of the thread terminating. I want to know what is the best way to deal with the exception handling below:
public List<WorkUnit> performModule(List<WorkUnit> listOfInputs)
throws ModuleException {
List<WorkUnit> listOfOutputs = new ArrayList<WorkUnit>();
for (WorkUnit mi : listOfInputs) {
WorkUnit mo=null;
try {
if (mi instanceof BulkOrder) {
mo = performModuleOperation(...);
} else if (mi instanceof Order) {
mo = performModuleOperation(...);
} else if (mi instanceof PreReleaseLoad) {
mo = performModuleOperation(...);
} else if (mi instanceof Load) {
mo = performModuleOperation(...);
}
listOfOutputs.add(mo);
} catch (OMSException e) {
if (e.shouldProcessFurther()) {
listOfOutputs.add((mo!=null) ? mo : mi);
}
//save error to database - code was removed
if ( e.getExceptionType().equals(ExceptionType.TECHNICAL)) {
if ( e instanceof ModuleException ) {
throw (ModuleException) e;
} else {
throw new ModuleException(e);
}
}
} catch (Throwable th) {
ModuleException me = new ModuleException(th);
ExceptionHandler.logException(me, (WorkUnit)mi,orderDelegate);
throw me;
}
}
return listOfOutputs ;
}
I have two major problems. 1) The catch for the Throwable object. I understand that they want to capture checked exceptions and unchecked exceptions. I guess that they want to check for Errors as well but the Sun documentation for exception handling specifically states that this is highly advised against. In the event you get a really serious error like the JVM running out of memory you may not be able to recover. This could be caught in a log file and I don't agree with it needing to be dealt with. Personally if you are tracking technical and applications exceptions errors doesn't seem like something that you would monitoring like any other exception. I could be wrong...
2) It isn't clear how the exceptions are being handled. In the code below the, which the exception throws to the code above it wraps a regular exception be it checked or unchecked into a custom exception and throws that. The code above looks for an OMSException which is the parent of every custom exception in the entire application. Is this a good design? You can see where they include a ExceptionType to the custom exception object. There already seems to be an functionality built into the existing exception handling of Java. If it is an application exception then throw a custom exception. If it is a technical exception, something is null when it isn't suppose to be or a database connection problem, then catch a unchecked exception from Java and react accordingly. This whole thing seems confusing. I just want to know what thoughts other have on the whole thing.
public Order performModuleOperation(Order order)
throws ModuleException {
try {
Map<String, Rule> rules = ...
}
catch (InductException ie) {
throw ie;
}
catch (Exception e) {
e.printStackTrace();
throw new InductException(e.toString(),e);
}
return order;
}
There are two ways to deal with a thread that exits with an unchecked exception. The first option is to run the thread from with in a try-catch block that catches all errors and exceptions:
Thread t = new MyThread();
try {
lauchThreadHere(t);
} catch (Throwable e) {
// log `e` or re-launch thread `t` or do something else.
}
Another way is to implement Thread.UncaughtExceptionHandler:
public class MyUeh implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
// log `e` or re-launch thread `t` or do something else.
}
}
Thread t = new MyThread();
t.setUncaughtExceptionHandler(new MyUeh());
lauchThreadHere(t);
From J2me doc we know that:
java.lang.InterruptedException Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it.
The question is if it's posible to get such exception if from one thread i call Thread.Interupt() for other thread where Run() method of other thread waiting on InputStream.Read(char[]buf) ?
The behavior of blocking read in response to thread interrupt is, in fact, undefined. See this long-standing bug for details. The short of it is that sometimes you get EOF, sometimes you get IOException.
Unfortunately, no, the java.io.* classes do not respond to interruptions when they are blocked in read or write methods. Typically what you have to do is close the stream and then handle the IOException that gets thrown. I have this pattern repeated throughout my code:
try {
for (;;) {
try {
inputStream.read(data);
thread.join();
}
catch (IOException exception) {
// If interrupted this isn't a real I/O error.
if (Thread.interrupted()) {
throw new InterruptedException();
}
else {
throw exception;
}
}
}
}
catch (InterruptedException exception) {
}
Alternatively the newer java.nio.* classes do handle interruptions better and generate InterruptedIOExceptions when they are interrupted. Note that this exception is derived from IOException and not from InterruptedException so you will probably need two catch clauses to handle either type of exception, one for InterruptedException and one for InterruptedIOException. And you'll want any inner IOException catch clause to ignore InterruptedIOExceptions.
Hey, I'm writing a network application, in which I read packets of some custom binary format. And I'm starting a background thread to wait for incoming data. The problem is, that the compiler doesn't let me to put any code throwing (checked) exceptions into run(). It says:
run() in (...).Listener cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException
I want the exception to kill the thread, and let it be caught somewhere in the parent thread. Is this possible to achieve or do I have to handle every exception inside the thread?
To be able to send the exception to the parent thread, you can put your background thread in a Callable (it allows throwing also checked exceptions) which you then pass to the submit method of some Executor. The submit method will return a Future which you can then use to get the exception (its get method will throw an ExecutionException which contains the original exception).
Caveat: this may not meet your needs if you have to use the exception mechanism.
If I understand you correctly, you don't actually need the exception to be checked (you've accepted the answer suggesting an unchecked exception) so would a simple listener pattern be more appropriate?
The listener could live in the parent thread, and when you've caught the checked exception in the child thread, you could simply notify the listener.
This means that you have a way of exposing that this will happen (through public methods), and will be able to pass more information than an exception will allow. But it does mean there will be a coupling (albeit a loose one) between the parent and the child thread. It would depend in your specific situation whether this would have a benefit over wrapping the checked exception with an unchecked one.
Here's a simple example (some code borrowed from another answer):
public class ThingRunnable implements Runnable {
private SomeListenerType listener;
// assign listener somewhere
public void run() {
try {
while(iHaveMorePackets()) {
doStuffWithPacket();
}
} catch(Exception e) {
listener.notifyThatDarnedExceptionHappened(...);
}
}
}
The coupling comes from an object in the parent thread having to be of type SomeListenerType.
This answer is based on Esko Luontola one but it provides a working example.
Unlike the run() method of the Runnable interface the call() method of Callable allows to throw some exceptions. Here is an implementation example :
public class MyTask implements Callable<Integer> {
private int numerator;
private int denominator;
public MyTask(int n, int d) {
this.numerator = n;
this.denominator = d;
}
#Override
// The call method may throw an exception
public Integer call() throws Exception {
Thread.sleep(1000);
if (denominator == 0) {
throw new Exception("cannot devide by zero");
} else {
return numerator / denominator;
}
}
}
Executor provides a mechanism to run a Callable inside a thread and to handle any kind of exceptions :
public class Main {
public static void main(String[] args) {
// Build a task and an executor
MyTask task = new MyTask(2, 0);
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
// Start task on another thread
Future<Integer> futureResult = threadExecutor.submit(task);
// While task is running you can do asynchronous operations
System.out.println("Something that doesn't need the tasks result");
// Now wait until the result is available
int result = futureResult.get();
System.out.println("The result is " + result);
} catch (ExecutionException e) {
// Handle the exception thrown by the child thread
if (e.getMessage().contains("cannot devide by zero"))
System.out.println("error in child thread caused by zero division");
} catch (InterruptedException e) {
// This exception is thrown if the child thread is interrupted.
e.printStackTrace();
}
}
}
What I do is to catch the exception in the thread and store it as a member variable of the Runnable. This exception is then exposed via a getter on the Runnable. I then scan all the threads from the parent to see if any had exceptions, and take the appropriate action.
If you really cannot do anything useful when the exception is raised you can wrap the checked exception in a RuntimeException.
try {
// stuff
} catch (CheckedException yourCheckedException) {
throw new RuntimeException("Something to explain what is happening", yourCheckedException);
}
the thread can't throw the exception to any other thread (nor to the main thread). and you cannot make the inherited run() method throw any checked exceptions since you can only throw less than the inherited code, not more.
If your thread's code throw a RuntimeExpection, you doesn't need to add run() throw Exception.
But use this solution only when appropriate because this can be a bad pratice:
http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html
Any RuntimeException or unchecked Exception can help you. Maybe you'll need to create your own RuntimeException
On the assumption that your code is in some kind of loop, you'd write:
public class ThingRunnable implements Runnable {
public void run() {
try {
while(iHaveMorePackets()) {
doStuffWithPacket()
}
} catch(Exception e) {
System.out.println("Runnable terminating with exception" + e );
}
}
}
The exception will automatically break you out of your loop, and at the end of the run() method, the thread will stop.
Use this Runnable to create your Thread:
public abstract class TryRunner implements Runnable{
protected abstract void tryToRun();
protected void onException(Exception e){}
#Override
final public void run() {
try{ tryToRun(); }catch(Exception e){ e.printStackTrace(); onException(e); }
}
}
Wrapping your exception inside a RuntimeException seems to do the trick.
someMethod() throws IOException
{
try
{
new Thread(() ->
{
try
{
throw new IOException("a checked exception thrown from within a running thread");
}
catch(IOException ex)
{
throw new RuntimeException("a wrapper exception", ex); // wrap the checked exception inside an unchecked exception and throw it
}
}).start();
}
catch(RuntimeException ex) // catch the wrapped exception sent from within the thread
{
if(ex.getCause() instanceof IOException)
throw ex.getCause; // unwrap the checked exception using getCause method and use it however you need
else
throw ex;
}
}