1

I have a list of objects that are processed using an executor service and everything is working correctly, because I am not explicitly returning anything in the thread that is run.

I want to change that - I want to be able to return a list of objects that contains all of the results from the calls. I think I need to use Futures, but I haven't found exactly what I need (I suspect this is a simple fix)

    ExecutorService executorService = null;
    //List<MyObject> allResults = new ArrayList<MyObject>();

    try {
        // Initialize the executor service
        executorService = Executors.newFixedThreadPool(5);

        // Process numbers
        for(String phoneNumber : allPhoneNumbers) {
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    logger.info("About to process: " + phoneNumber);
                    sendSms(phoneNumber, amqpMessage.getMessage()); // This would return MyObject = sendSms(...)
                }

            });
        }

        // No more threads can be added
        executorService.shutdown();

        // Wait until threads are finished and terminate
        executorService.awaitTermination(amqpMessage.getAllPhoneNumbersGettingMessage().size(), TimeUnit.MINUTES);
user10776719
  • 301
  • 4
  • 15

1 Answers1

0

Use the overloaded submitmethod that takes a Callable:

  ExecutorService#submit(java.util.concurrent.Callable<T>)

It returns a Future<T>, which eventually returns the value of your calculation.

michid
  • 10,536
  • 3
  • 32
  • 59