Медленно работает Callable

222
24 июня 2018, 02:50

Столкнулся с проблемой: медленно выполняется программа, использующая Callable. Вернее так: ответ выдается сразу, но потом она очень долго думает над чем-то. В чем проблема?

         public class Driver {
            public static int for_each (ArrayList<Integer> array,
                                        Executor executor, Reduce reduce,
                                        int threads){
                ///////
                ExecutorService call = null;
                final int len = array.size();
                int result = 0;
                final int cellsForThread = len / threads;
                int firstIndex = 0;
                final Thrd[] multiplierThreads = new Thrd[threads];
                ArrayList<Future<Integer>> res = new ArrayList<Future<Integer>>();
                for (int threadIndex = threads - 1; threadIndex >= 0; --threadIndex) {
                    int lastIndex = firstIndex + cellsForThread;
                    if (threadIndex == 0) {
                        lastIndex = array.size();
                    }
                    multiplierThreads[threadIndex] =
                            new Thrd(array, firstIndex, lastIndex, result, executor,
                                    reduce);
                    call = Executors.newCachedThreadPool();
                    res.add(call.submit(multiplierThreads[threadIndex]));
                    firstIndex = lastIndex;
                }
                call.shutdown();
                return reduce.process(res);
            }
            public static void main(String[] args) {
                ArrayList<Integer> in = new ArrayList<>();
                for (int i = 0; i <= 5; i++){
                    in.add(-i);
                }
                MinExecutor minExecutor  = new MinExecutor();
                MinReduce minReduce = new MinReduce();
                System.out.println(for_each(in,minExecutor,minReduce,10));
            }
        }
        public class Thrd implements Callable<Integer> {
                private final ArrayList<Integer> in;
                private final int first;
                private final int last;
                private int result;
                private final Executor exec;
                private final Reduce red;
               public Thrd(ArrayList<Integer> in, int first, int last, int result,
               Executor exec, Reduce red){
                    this.in = in;
                    this.first = first;
                    this.last = last;
                    this.result = result;
                    this.exec = exec;
                    this.red = red;
                }
                @Override
                public Integer call(){
                       return exec.process(in, first,last);
                }
        }
    public class MinExecutor implements Executor {
        public int process (ArrayList<Integer> in, int firstindex,
                            int secondindex){
            int min;
            min = in.get(0);
            for (int i = firstindex; i < secondindex; i++){
                  for (int j = i + 1; j < secondindex; j++){
                      if (min > in.get(j)){
                          min = in.get(j);
                      }
                  }
            }
            return min;
        }
    }
public class MinReduce implements Reduce {
    public int process (ArrayList<Future<Integer>> in){
        int min = 0;
        try {
               min = in.get(0).get();
               for (Future<Integer> i : in) {
                   int tmp = i.get();
                   if (min > tmp){
                       min = tmp;
                   }
               }
           }catch (ExecutionException ex){
               System.out.println(ex.getMessage());
           }catch (InterruptedException exe){
               System.out.println(exe.getMessage());
           }
           return min;
    }
}
public interface Executor {
    public int process (ArrayList<Integer> in, int firstindex,
                        int secondindex);
}
public interface Reduce {
    public int process (ArrayList<Future<Integer>> in);
}

Классы были вырезаны из разных пакетов, т.к. я не знаю, как сюда файлики с кодом добавлять. Заранее извиняюсь за форматирование, т.к. это мой первый опыт использования данного ресурса.

Answer 1

Я думал, что завершит сразу все элементы, которые я передал исполнителю. Оказалось, что их все надо завершать отдельно)))). Решение: внести shutdown() в цикл!

READ ALSO
Чем отличаются ConnectTimeout и ConnectionRequestTimeout?

Чем отличаются ConnectTimeout и ConnectionRequestTimeout?

Есть пример запроса через RestTemplate поведение которого конфигурируется через ClientHttpRequestFactory и RequestConfigПри создании объекта RequestConfig задаются три...

230
подключение oracle database к приложению javaFX

подключение oracle database к приложению javaFX

установил Oracle Database 11g + SQLDeveloperСоздал нового пользователя и connection

199
Объясните на пальцах, в чем отличие Thread, Handler, Runnable и AsyncTask?

Объясните на пальцах, в чем отличие Thread, Handler, Runnable и AsyncTask?

Пожалуйста, объясните по простому в чем отличие Thread, Handler, Runnable и AsyncTask?

217
Перенести ветку из одного репозитария в другой

Перенести ветку из одного репозитария в другой

Есть репозитарийСоздал ветку, сделал какие-то правки

275