Stream Exception

I made a multi-threaded program. In it, the main thread starts 10 threads, but the problem occurs whenever an exception occurs in one of the threads, the whole application stops.

  • But I want that whenever an exception occurs on one thread, only that thread should be stopped and the other threads keep running. How can i do this?

  • Second, I want the main thread to stop only after all 10 threads have finished. How can i do this?

+2


source to share


5 answers


You can use an ExecutorService (containing multiple threads) to process your individual work items by calling submit (). The submit method returns a Future that encapsulates either the processing result or any excluded browser . In other words, threads inside yours ExecutorService

will not terminate if an exception occurs.

Example

First, create an executor service containing multiple threads:

ExecutorService execService = Executors.newFixedThreadPool(5);

      

Define the work item that we want to represent as Callable

:



public class MyWorkItem implements Callable<Integer> {
  public Integer call() throws Exception {
    int result = new Random().nextInt(5);

    // Randomly fail.
    if (result == 0) {
      throw new IllegalArgumentException("Fail!");
    }

    return result;
  }
}

      

Submit some work to the executor service and save Future<Integer>

for each Callable<Integer>

.

List<Future<Integer>> futures = new LinkedList<Future<Integer>>();

for (int i=0; i<10; ++i) {
  futures.add(execService.submit(new MyWorkItem()));
}

      

Now looping through the futures trying to get the result of each work item (we could use for that CompletionService

).

for (Future<Integer> future : futures) {
  try {
    Integer result = future.get();
  } catch(Exception ex) {
    // Handle exception.
  }
}

      

+4


source


At the end of the main method, you must call join

on every running thread.



By the way: if you want to handle exceptions from your threads you can use Thread.setDefaultUncaughtExceptionHandler ()

+3


source


Surround with try / catch all

public void run() {
    try {
        ....
    } catch( Exception e ){}
}

      

Although I would rather try to determine the reasons for these exceptions.

+1


source


For # 1, if this is your intended goal, you should consider how you handle this exception and what types of exceptions you expect. If these are application errors, you can define a more useful way to catch the exception at the individual thread level and feed the important information back to the parent thread. Alternatively, a thread pool management solution for you might be the best method to work with, as @Adamski pointed out, for example the ExecutorSerivce implementation of ThreadPoolExecutor, however you will need to understand the exceptions and if they can be prevented with some additional logic if not then the best the way to effectively manage your work is the way to go.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html

For # 2, join () or use a thread pool to manage them.

+1


source


Regarding your first point, I would suggest that you gracefully exit the thread when you throw an exception, i.e. catch it in the stream (and don't let it bubble up to jvm).

0


source







All Articles