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

Detailed introduction of Java thread pool

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "Java thread pool detailed introduction". In daily operation, I believe many people have doubts about Java thread pool detailed introduction. Xiaobian consulted all kinds of information and sorted out simple and easy operation methods. I hope to help you answer the doubts of "Java thread pool detailed introduction"! Next, please follow the small series to learn together!

The reason for using thread pools is that using new Thread has disadvantages in large projects:

Poor performance every time a new Thread object is created

Threads lack unified management, new threads may be unlimited, competing with each other, which may cause excessive use of system resources and lead to OOM

Lack of more features such as regular execution

Benefits of thread pools:

Reuse existing threads, reduce object creation, death overhead, good performance

It can effectively control the maximum number of concurrent threads, improve the utilization of system resources, and avoid excessive resource competition and blocking.

Provide timed execution, periodic execution, single thread, concurrent number control and other functions

State transitions for state pools

Class inheritance relationships for thread pools

Executor is a top-level interface, in which only one method execute(Runnable) is declared, the return value is void, the parameter is Runnable type, literally understood, that is, used to execute the task passed in.

ExecutorService inherits the Executor interface and declares methods such as submit, invokeAll, invokeAny, and shutDown.

AbstractExecutorService implements the ExecutorService interface and basically implements all the methods declared in ExecutorService.

ThreadPoolExecutor inherits the class AbstractExecutorService.

ThreadPoolExecutor method description

execute() is actually a method declared in the Executor, implemented specifically in ThreadPoolExecutor. This method is the core method of ThreadPoolExecutor. Through this method, you can submit a task to the thread pool for execution.

The submit() method is a method declared in ExecutorService. It has been implemented in AbstractExecutorService. It is not rewritten in ThreadPoolExecutor. This method is also used to submit tasks to the thread pool. However, it is different from the execute() method. It can return the result of task execution. If you look at the implementation of the submit() method, you will find that it is actually the execute() method called, but it uses Future to obtain the result of task execution.

shutdown() gracefully closes the thread pool

shutdownNow() Forces thread pool closure

There are many other methods: getQueue(), getPoolSize(), getActiveCount(), getCompletedTaskCount(), etc. Methods to get properties related to the thread pool can be used for thread pool monitoring. Interested friends can consult the API themselves.

For more detailed instructions on ThreadPoolExecutor configuration, click View: Still creating thread pools with Executors? Beware of memory overflow

scheduledExecutorService usage@Slf4jpublic class ThreadPoolExample {

public static void main(String[] args) {

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

//Delaying tasks// executorService.schedule(()->// log.warn("schedule run"), 3, TimeUnit.SECONDS);

//fixed-rate task executorService.scheduleAtFixedRate(() -> log.warn("schedule run"), 1, 3, TimeUnit.SECONDS);// executorService.shutdown();

// Timer can also perform scheduled tasks, but it is recommended to use Scheduled ExecutorService// Timer timer = new Timer();// timer.schedule(new TimerTask() {// @Override// public void run() {// log.warn("timer run");// }// }, new Date(), 5 * 1000); }}

Special Note: If an exception is thrown during the execution of a periodic task executed through the Scheduled ExecutorService, the Scheduled ExecutorService will stop executing the task and will not execute the task periodically again. So if you want to keep the task cycle running, you need to catch all possible exceptions.

Thread pool core thread count configuration recommendations

CPU-intensive tasks: squeeze CPU as much as possible, reference value set to NCPU+1

IO-intensive tasks: Reference value can be set to 2*NCPU

Related thread pools Spring's asynchronous thread pool

TaskExecutive is an interface to the Spring asynchronous thread pool, inheriting the Java.util.concurrent. Executive interface.

Spring already implemented asynchronous thread pool (TaskExecutor implementation class):

SimpleAsyncTaskExecutor: Not a true thread pool, this class does not reuse threads, and creates a new thread every time it is invoked.

SyncTaskExecutor: This class does not implement asynchronous invocation, just a synchronous operation. Only for places where multithreading is not required

ConcurrentTaskExecutor: Adaptor class for Executor, not recommended. Consider using this class only if ThreadPoolTaskExecutor does not meet the requirements

SimpleThreadPoolTaskExecutor: is the class of SimpleThreadPool of Quartz. This class is needed if the thread pool is used by both quartz and non-quartz

ThreadPoolTaskExecutor: Most often used, recommended. This is essentially a wrapper around java.util.concurrent. ThreadPoolExecutive

Use of Spring's asynchronous thread pool

@Async marks the method as an asynchronous method. After Spring scans it, when the method is executed, a new thread will be started to execute it. It is very simple.

For @Async annotation to work, you also need to configure @EnableAsync in Spring Boot's main program.

Functions modified by @Async should not be defined as static, so asynchronous calls do not take effect.

At this point, the study of "Java thread pool details" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

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

Internet Technology

Wechat

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

12
Report