Code for a blogpost
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB

  1. package net.jrtechs;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Vector;
  5. import java.util.concurrent.*;
  6. import java.util.stream.Collectors;
  7. public class ThreadPoolExecutor<E> extends ParallelExecutor<E>
  8. {
  9. @Override
  10. public List<E> runTasks(Vector<Work<E>> tasks)
  11. {
  12. ExecutorService executor = Executors.newCachedThreadPool();
  13. List<Callable<E>> callables = new ArrayList<Callable<E>>();
  14. for(Work<E> work: tasks)
  15. {
  16. Callable<E> c = new Callable<E>() {
  17. @Override
  18. public E call() throws Exception {
  19. return work.runTask();
  20. }
  21. };
  22. callables.add(c);
  23. }
  24. List<E> results = new ArrayList<>();
  25. try
  26. {
  27. List<Future<E>> futures = executor.invokeAll(callables);
  28. for(Future<E> future: futures)
  29. {
  30. try {
  31. results.add(future.get());
  32. } catch (ExecutionException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }
  37. catch (InterruptedException e)
  38. {
  39. e.printStackTrace();
  40. }
  41. return results;
  42. }
  43. }