Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the schemes for Java to execute tasks in parallel?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the solutions for parallel execution of tasks in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Background

Recently, in troubleshooting the production environment, it is found that the RPC call timeout is reported from time to time on the product details API. The check code shows that the query activities in the interface take a long time and are all executed serially. After careful inspection, it is found that it can be changed to parallel execution, thus shortening the query time of the interface.

For example, for our product details interface, we need to display activity tags such as vertical reduction, ladder reduction, group purchase and so on. You need to query three different activity information, and then assemble the activity tag information.

If each query takes 1 second, it will take at least 3 seconds to call the whole interface in a serial way, which is unacceptable to us. In fact, in jdk, it provides us with several very convenient ways to execute tasks in parallel.

CountDownLatch

ExecutorService.invokeAll ()

Fork/Join divide and conquer is a bit like the shadow of MapReduce. Those who are interested can find out for themselves.

Improvement scheme

Code example:

Private void assemblyActivityTag (CartItemDTO itemDTO) {/ 1. It takes 1 s / 2 to query the activity information. It takes 1 s / 3 to query ladder full subtraction activity information. It takes 1 s / 4 to query the information of group buying activities. It takes 1 s / / serial execution time to assemble activity tag information, which takes 4 s}

CountDownLatch

Private void assemblyActivityTag (CartItemDTO itemDTO) {ExecutorService executorService = Executors.newCachedThreadPool (); CountDownLatch latch = new CountDownLatch (3); executorService.execute (new Runnable () {@ Override public void run () {/ / 1. Query latch.countDown ();}}); executorService.execute (new Runnable () {@ Override public void run () {/ / 2. Query ladder full subtraction activity information latch.countDown ();}}); executorService.execute (new Runnable () {@ Override public void run () {/ / 3. Query group purchase activity information latch.countDown ();}}); try {/ / be sure to add timeout time to prevent blocking of the main thread latch.await (3000 TimeUnit. MILLISECONDS);} catch (InterruptedException e) {e.printStackTrace ();} / 4. Wait for all subtasks to complete and assemble the activity tag information / / 5. Close thread pool executorService.shutdown ();}

ExecutorService.invokeAll ()

Private void assemblyActivityTag (CartItemDTO itemDTO) {ExecutorService executorService = Executors.newCachedThreadPool (); List tasks = Lists.newArrayList (); tasks.add (new Callable () {@ Override public String call () throws Exception {/ / 1. Query return null;}); tasks.add (new Callable () {@ Override public String call () throws Exception {/ / 2. Query ladder full reduction activity information return null;}}); tasks.add (new Callable () {@ Override public String call () throws Exception {/ / 3. Query group purchase activity information return null;}}); try {List futureList = executorService.invokeAll (tasks, 3000, TimeUnit.MILLISECONDS); for (Future future: futureList) {/ / get thread execution result try {String activityTag = future.get () } catch (ExecutionException e) {e.printStackTrace ();} catch (InterruptedException e) {e.printStackTrace ();} / / 4. Assembly activity tag information / / 5. Close thread pool executorService.shutdown ();} Note and difference

When using CountDownLatch, use a thread-safe container to handle the return values of child threads as much as possible to avoid dirty data in the case of multiple threads.

If you want to know the corresponding return value of each child thread, the ExecutorService.invokeAll () method is indistinguishable and can only be matched by the order of the return values.

When using the above two methods, remember to set the timeout to prevent the execution of subtasks from taking too long and blocking the main thread task

When the thread pool runs out, remember to shutdown ()

Java executes tasks in parallel demo

Call multiple methods or services in a method at the same time and wait for all the results to return

Package com.test.demo;import org.junit.Test;import java.util.concurrent.CompletableFuture;public class TestFuture {@ Test public void testA () {CompletableFuture future3 = CompletableFuture.supplyAsync (()-> c ()); CompletableFuture future1 = CompletableFuture.supplyAsync (()-> a ()); CompletableFuture future2 = CompletableFuture.supplyAsync (()-> b ()) Try {/ / get the result of parallel execution task System.out.println (future3.get ()); System.out.println (future1.get ()); System.out.println (future2.get ());} catch (Exception e) {}} public String a () {try {Thread.sleep (1000) } catch (Exception e) {} return "a";} private String b () {try {/ / simulated business execution time Thread.sleep (2000);} catch (Exception e) {} return "b" } private String c () {try {/ / simulated business execution time Thread.sleep (5000);} catch (Exception e) {} return "c";}}

Test results:

From the execution results, we can see that it takes a total of 5 seconds. If the synchronization is executed, the time consuming should be 8 seconds.

This is the end of the content of "what are the plans for Java to execute tasks in parallel". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report