Java multithreading causes CPU usage to be 100% resolved and thread pool to be closed correctly
intro
Scenario: 10 million table data imported into memory database, query by page size 10000, multithreading, 15 threads running. Use the ExecutorService executor = Executors. NewFixedThreadPool (15) local ran after a period of time, found that the computer CPU increased, finally 100% CPU card dead, memory usage is as high as 80%.
Troubleshoot problems
Debug finds that although a thread pool with a fixed length of 15 is created, the List iterated in For will continue to be added to every waiting task in the LinkedBlockingQueue() queue due to the large amount of data. Therefore, whether it is CPU preemption of thread number, or memory consumption is extremely high. So you can control the upper limit of the wait queue LinkedBlockingQueue.
solution
Use AtomicLong to check whether the thread has completed, and then execute executor.submit() to submit a new task to the lead queue. The pseudo-code is as follows:
private AtomicLong threadNum = new AtomicLong(0); public void init() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(15); Integer total = accountMapper.selectCount(new QueryWrapper<>()); Integer pageSize = 10000; Integer pageCount = (total + pageSize -1)/pageSize; // Page size INTEGER pagecount = (total + pagesize-1)/pagesize; // Total number of pages for (Integer start = 1; start <= pageCount; start++) { List<Account> list = accountMapper.selectPage(new Page<>(start, pageSize), query).getRecords(); // Wait for the Thread task to complete, set 30, the number of running threads is 15, the number of waiting queue threads is 15 while (threadNum.get() >= 30){thread.sleep (5000); } / / open a thread + 1 threadNum incrementAndGet (); executor.submit(() -> {try {// dealMessage(list); / / task - 1 threadNum. DecrementAndGet (); } catch (Exception e) { e.printStackTrace(); }}); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.DAYS); }
The effect is to keep the CPU between 15 and 45%, and the memory usage is only 45%.
So far I can only think of such a way to control the upper limit of waiting queue LinkedBlockingQueue, there is a better way to let me know, thank you!
2021-02-03- The dividing line has recently used multi-threaded development and found that there are still many ways to control it. A simple Semaphore token flow limiting control using java is also possible.
Multi-threading:
- The thread pool must be closed before the main thread can be finished (and the interface will return). finally {executorService.shutdown(); }
- The main thread waits to ensure that all the subthread tasks of multiple threads have completed, and then ends. -> executorService.awaitTermination(1, TimeUnit.DAYS);
- semaphore token flow limiting controls the fixedThread thread pool, which in this case is a maximum of 2 threads working at the same time
- Execute () The difference between fixedThread.execute() and fixedThread.submit() is that the latter returns the result, but the latter catches the exception message and cannot be thrown to the main thread.
public static void main(String[] args) { final List<String> tableNames = new ArrayList<>(); tableNames.add("a"); tableNames.add("b"); tableNames.add("c"); tableNames.add("d"); tableNames.add("e"); tableNames.add("f"); final Semaphore semaphore = new Semaphore(2); final ExecutorService fixedThread = Executors.newCachedThreadPool(); for (final String tableName: tableNames) {// block, acquire token try {semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } //do fixedThread.execute(() -> { //can throw ex log final ExecutorService executorService = Executors.newCachedThreadPool(); try { executorService.submit(() -> { //can't throw ex log //int i = 1/0; System.out.println("tableName2:" + tableName); }); //int i = 1/0; System.out.println("tableName:" + tableName); } catch (Exception e) { e.printStackTrace(); } finally { executorService.shutdown(); try { executorService.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } semaphore.release(); System.out.println("semaphore.release"); }}); } // Remember to close the thread pool fixedThread.shutdown(); try { fixedThread.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(" Main thread...") ); }
Print result
tableName:b tableName2:b tableName:a tableName2:a semaphore.release semaphore.release tableName:d tableName2:d tableName:c semaphore.release tableName:e tableName2:c semaphore.release tableName:f tableName2:e semaphore.release tableName2:f semaphore.release Main thread...
To this article on Java multithreading caused by the CPU occupancy 100% solution and thread pool the correct way to close the article is introduced to this, more related Java multithreading CPU occupancy 100% content please search the previous articles of the script home or continue to browse the following related articles hope that you will support the script home in the future!
- Java's elegant method of closing thread pools
- How to close threads and thread pools in Java
- The difference between shutdown and shutdownNow when Java shuts down thread pools
- The most useful guide to creating and closing thread pools in java
- java elegantly closes the thread pool scheme
- Should java thread pools be closed after use
- Closing of thread pools in java
Related article
-
Java implementation of the intermediate expression example code
This article mainly introduces the Java implementation of the sequence expression example code, the need for friends can refer to the next2018-08-08 -
Simple use examples of try and throw
After a while, it will always be a little rusty to try, especially wrote a program to test the following, sometimes throw is thrown out of the bottom, you do not deal with, the default throw2013-08-08 -
Java Case Sharing - Collection nesting
This article mainly introduces the Java case sharing - collection nesting, through the case to create an ArrayList collection, storage of three elements, each element is HashMap, each HashMap key and value are String, and traversal, the actual operation content needs a small partner can refer to2022-04-04 -
The construction of web application based on springMvc+hibernate
The following Xiaobian will bring you a web application construction based on springMvc+hibernate. Xiaobian feel very good, now to share with you, but also to give you a reference. Let's take a look2017-10-10 -
Java Spring annotation development case detailed explanation
This article mainly introduces the Java Spring annotation development case detailed explanation, this article through a brief case, explains the understanding and use of the technology, the following is the detailed content, the need of friends can refer to2021-07-07 -
springmvc accesses pages in WEB-INF directly without going through the controller
This article mainly introduces springmvc directly without controller access to WEB-INF page problems, has a good reference value, I hope to help you. If there are mistakes or incomplete areas, please feel free to comment2022-02-02 -
The difference between microservices and distributed
In this article, Xiaobian has sorted out the difference between microservices and distribution and a summary of relevant knowledge points for interested friends to learn.2019-07-07 -
jfreechart's method of drawing a line graph
This article mainly introduces the method of jfreechart drawing line line in detail, the example code in the article is very detailed, has a certain reference value, interested partners can refer to it2018-06-06 -
SpringBoot uses AOP to implement detailed statistics on the number of global interface accesses
This article mainly introduces SpringBoot through AOP to achieve the number of global interface access statistics, the article from the related issues to expand the full text details, has a certain reference value, the need of small partners can refer to2022-06-06 -
The usage of super and this in Java is detailed
this article mainly introduces the usage of super and this in Java in detail, this article through the example code to give you a very detailed introduction, for everyone's study or work has a certain reference value, need friends can refer to it2020-08-08
Latest comments