Search code examples
javamultithreadingcluster-analysisthreadgroup

Clustering using Threads in Java


I have a job that takes too long time in Java. So I want to divide this job into threads and run them. After the threads finishes their jobs, returns to my service and Service give them new jobs. ThreadGroup is suitable for this or any other recommendation?


Solution

  • Check out the ExecutorCompletionService - it does exactly this.

    Example: [pulled from Java 6 API JavaDocs]

     void solve(Executor e, Collection<Callable<Result>> solvers)
         throws InterruptedException, ExecutionException {
           CompletionService<Result> ecs
               = new ExecutorCompletionService<Result>(e);
           for (Callable<Result> s : solvers)
               ecs.submit(s);
           int n = solvers.size();
           for (int i = 0; i < n; ++i) {
               Result r = ecs.take().get();
               if (r != null)
                   use(r);
           }
       }