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.

final ExecutorService executor = Executors.newFixedThreadPool(numThreads);
final Collection<Future<JsonNode>> futures = new LinkedList<Future<JsonNode>>();

//Write a Loop if you want
final Callable<TYPE> callable = new MyClass();
futures.add(executor.submit(callable));
executor.shutdown();

// We need to monitor the queries for their data being returned.
for (final Future<?> future : futures) {
	try {
		final TYPE val = (TYPE) future.get();
	} catch (final InterruptedException e) {
	} catch (final ExecutionException e) {
	}
}

 

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

package mypackage;

import java.util.concurrent.Callable;
import org.apache.log4j.Logger;

public class MyClass implements Callable<JsonNode> {

    static final Logger logger = Logger.getLogger(MyClass.class);

    MyClass() {
    }

    /**
     * This is how each caller queries for the data. It can be called many times and runs on threads from the calling class
     * So data is returned as it gets it.
     */
    @Override
    public TYPE call() throws Exception {
        try {
                  return null;
        } catch (final Exception e) {
            return null;
        }
    }
}