Java: ExecutorService / Future

(Last Updated On: )

If you want to spin off a bunch of threads and manage them and their responses effectively you can do it this way.

  1. final ExecutorService executor = Executors.newFixedThreadPool(numThreads);
  2. final Collection<Future<JsonNode>> futures = new LinkedList<Future<JsonNode>>();
  3.  
  4. //Write a Loop if you want
  5. final Callable<TYPE> callable = new MyClass();
  6. futures.add(executor.submit(callable));
  7. executor.shutdown();
  8.  
  9. // We need to monitor the queries for their data being returned.
  10. for (final Future<?> future : futures) {
  11. try {
  12. final TYPE val = (TYPE) future.get();
  13. } catch (final InterruptedException e) {
  14. } catch (final ExecutionException e) {
  15. }
  16. }

 

The callable works with a class so you will need that.

  1. package mypackage;
  2.  
  3. import java.util.concurrent.Callable;
  4. import org.apache.log4j.Logger;
  5.  
  6. public class MyClass implements Callable<JsonNode> {
  7.  
  8. static final Logger logger = Logger.getLogger(MyClass.class);
  9.  
  10. MyClass() {
  11. }
  12.  
  13. /**
  14. * This is how each caller queries for the data. It can be called many times and runs on threads from the calling class
  15. * So data is returned as it gets it.
  16. */
  17. @Override
  18. public TYPE call() throws Exception {
  19. try {
  20.                   return null;
  21. } catch (final Exception e) {
  22. return null;
  23. }
  24. }
  25. }