1

I'm trying to use For loop with multi-threading in Java 1.6. I tried to use streams but apparently it was added in Java 1.8, so i tried to useExecutorService and Future but i can't make it work.

What i want is just make this code multi-threaded with fixed number of threads.

for (ExampleType ex : exampleData) {
    exampleFunction(ex.getSomeData());
}

What i tried and didn't work, found it somewhere from google

final ExecutorService testExecutor = Executors.newFixedThreadPool(10); // just 10 thread
final List<Future<?>> executeDatas = new ArrayList<List>();

for (ExampleType ex : exampleData) {
    Future<?> executeData = testExecutor.submit(() -> {
        exampleFunction(ex.getSomeData());
    });
    executeDatas.add(executeData);
}

for (Future<?> executeData : executeDatas) {
    executeData.done(); // do i need to write stuff here? i don't have done() function
}

It probably would've worked but says diamond operator is not supported in -source 1.6. Yeah i'm not sure how to handle from here and been stuck. Any help is appreciated

3
  • That code won't work in Java 6 because of the lambda. You'd need to write it an anonymous class. Commented Apr 26, 2018 at 18:34
  • executeData.get(); to wait for the results in the order you submitted them. If you want them in completion order, use a CompletionService. Commented Apr 26, 2018 at 18:35
  • 2
    Why even use Java 1.6? It is more than 10 years old. Commented Apr 26, 2018 at 18:35

1 Answer 1

3

For some reason, noone shows the transformed code, so I'll do it:

final ExecutorService testExecutor = Executors.newFixedThreadPool(10);
final List<Future<?>> executeDatas = new ArrayList<Future<?>>();

for (ExampleType ex : exampleData) {
    Future<?> executeData = testExecutor.submit(new Runnable() {
        @Override
        public void run() {
            exampleFunction(ex.getSomeData());
        }
    });
    executeDatas.add(executeData);
}

for (Future<?> executeData : executeDatas) {
    // calling get in loop to effectively wait for all the futures to finish
    executeData.get();
}

Three changes are made:

  1. ArrayList<List> replaced with with ArrayList<Future<?>>
  2. Lambda replaced with anonymous class instantiation
  3. .done() changed to .get() to wait for all the futures to finish execution
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.