Parallelize a for loop in Java using multithreading

I am very new to java and I want to parallelize the loop of nested loops using the executor service or use any other method in java. I want to create some fixed number of threads so that the processor is not completely received by threads.

for(SellerNames sellerNames : sellerDataList) { for(String selleName : sellerNames) { //getSellerAddress(sellerName) //parallize this task } } 

seller sizeDataList = 1000 and seller sizeNames = 5000.

Now I want to create 10 threads and assign an equal piece of the task for each thread the same way. This is for i'th sellerDataList, the first thread should get the address for 500 names, the second thread should get the address for the next 500 names, etc.
What is the best way to do this job?

+5
source share
1 answer

There are two ways to run it in parallel: threads and artists.

Using threads

You can use parallel threads and leave the rest in jvm. In this case, you do not have too much control over what happens when. On the other hand, your code will be easy to read and maintain:

  sellerDataList.stream().forEach(sellerNames -> { Stream<String> stream = StreamSupport.stream(sellerNames.spliterator(), true); // true means use parallel stream stream.forEach(sellerName -> { getSellerAddress(sellerName); }); }); 

Using ExecutorService

Suppose you want 5 threads and you want to wait for the task to complete. Then you can use a fixed thread pool with 5 threads and use Future -s so that you can wait until they are executed.

  final ExecutorService executor = Executors.newFixedThreadPool(5); // it just an arbitrary number final List<Future<?>> futures = new ArrayList<>(); for (SellerNames sellerNames : sellerDataList) { for (final String sellerName : sellerNames) { Future<?> future = executor.submit(() -> { getSellerAddress(sellerName); }); futures.add(future); } } try { for (Future<?> future : futures) { future.get(); // do anything you need, eg isDone(), ... } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } 
+8
source

Source: https://habr.com/ru/post/1267222/


All Articles