views:

142

answers:

5

I have made a multi-threading program. In it, the main thread starts 10 threads but the problem is whenever an exception occured in one of the threads, the whole application gets stopped.

  1. But I want that whenever an exception occurred in one thread, only that thread should gets stopped and other threads keep working. How can I do that?

  2. Second, I want that the main thread should stopped only after all the 10 threads finished. How can I do that?

+3  A: 

At the end of your main method you should call join on every started thread.

By the way: If you want to handle the exceptions of your threads, you can use Thread.setDefaultUncaughtExceptionHandler()

tangens
+3  A: 

You could use an ExecutorService (containing multiple threads) to process your individual items of work by calling submit(). The submit method returns a Future, which will encapsulate either the result of the processing or any exception thrown. In other words, the threads within your ExecutorService will not terminate if an exception occurs.

Example

First create an executor service containing more than one thread:

ExecutorService execService = Executors.newFixedThreadPool(5);

Define the item of work we wish to submit as a 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 for the executor service to do, and store the 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 iterate over the futures attempting to retrieve the result of each work item (we could use a CompletionService for this).

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

Surround with try/catch all

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

Although I would better try to identify the reasons for those exceptions.

OscarRyz
A: 

Concerning your first point I would suggest that you gracefully exit a thread when an exception is thrown, that is, catch it within the thread (and not let it bubble up to the jvm).

Yaneeve
+1  A: 

For #1, if this is your intended goal you should consider how you are handling that exception and what types of exceptions your are expecting. If these are application faults you can determine a more useful way to catch the exception at the individual thread level and feed and important information back to the parent thread. Alternatively a solution for managing the thread pool for you may be a better method to go with as @Adamski pointed out, like the implementation of the ExecutorSerivce ThreadPoolExecutor, however you will need to understand the exceptions and if they can be prevented with some additional logic if not then having a better way to manage your jobs effectively 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.

Sean