Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 546987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:55:29+00:00 2026-05-13T10:55:29+00:00

Say I have a task like: for(Object object: objects) { Result result = compute(object);

  • 0

Say I have a task like:

for(Object object: objects) {
    Result result = compute(object);
    list.add(result);
}

What is the easiest way to parallelize each compute() (assuming they are already parallelizable)?

I do not need an answer that matches strictly the code above, just a general answer. But if you need more info: my tasks are IO bound and this is for a Spring Web application and the tasks are going to be executed in a HTTP request.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T10:55:30+00:00Added an answer on May 13, 2026 at 10:55 am

    I would recommend taking a look at ExecutorService.

    In particular, something like this:

    ExecutorService EXEC = Executors.newCachedThreadPool();
    List<Callable<Result>> tasks = new ArrayList<Callable<Result>>();
    for (final Object object: objects) {
        Callable<Result> c = new Callable<Result>() {
            @Override
            public Result call() throws Exception {
                return compute(object);
            }
        };
        tasks.add(c);
    }
    List<Future<Result>> results = EXEC.invokeAll(tasks);
    

    Note that using newCachedThreadPool could be bad if objects is a big list. A cached thread pool could create a thread per task! You may want to use newFixedThreadPool(n) where n is something reasonable (like the number of cores you have, assuming compute() is CPU bound).

    Here’s full code that actually runs:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class ExecutorServiceExample {
        private static final Random PRNG = new Random();
    
        private static class Result {
            private final int wait;
            public Result(int code) {
                this.wait = code;
            }
        }
    
        public static Result compute(Object obj) throws InterruptedException {
            int wait = PRNG.nextInt(3000);
            Thread.sleep(wait);
            return new Result(wait);
        }
    
        public static void main(String[] args) throws InterruptedException,
            ExecutionException {
            List<Object> objects = new ArrayList<Object>();
            for (int i = 0; i < 100; i++) {
                objects.add(new Object());
            }
    
            List<Callable<Result>> tasks = new ArrayList<Callable<Result>>();
            for (final Object object : objects) {
                Callable<Result> c = new Callable<Result>() {
                    @Override
                    public Result call() throws Exception {
                        return compute(object);
                    }
                };
                tasks.add(c);
            }
    
            ExecutorService exec = Executors.newCachedThreadPool();
            // some other exectuors you could try to see the different behaviours
            // ExecutorService exec = Executors.newFixedThreadPool(3);
            // ExecutorService exec = Executors.newSingleThreadExecutor();
            try {
                long start = System.currentTimeMillis();
                List<Future<Result>> results = exec.invokeAll(tasks);
                int sum = 0;
                for (Future<Result> fr : results) {
                    sum += fr.get().wait;
                    System.out.println(String.format("Task waited %d ms",
                        fr.get().wait));
                }
                long elapsed = System.currentTimeMillis() - start;
                System.out.println(String.format("Elapsed time: %d ms", elapsed));
                System.out.println(String.format("... but compute tasks waited for total of %d ms; speed-up of %.2fx", sum, sum / (elapsed * 1d)));
            } finally {
                exec.shutdown();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 295k
  • Answers 296k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer It is the most generally used for library purpose. The… May 13, 2026 at 6:59 pm
  • Editorial Team
    Editorial Team added an answer I made the Company class abstract and it build correctly.… May 13, 2026 at 6:59 pm
  • Editorial Team
    Editorial Team added an answer The second is 2000-times more preferable to the first. In… May 13, 2026 at 6:59 pm

Related Questions

This question is coded in pseudo-PHP, but I really don't mind what language I
It's a trivial task to find out if an object is referenced by something
Let's say I have a class Voucher: public class Voucher { public Guid Id
I've been working in PHP5 for a couple of years now and have developed
I have developed a taxonomy for a site that I've been working on that

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.