Java interview thread pool

The following are some common thread pool questions I have compiled in Java interviews, and I will share them with you now.
(Learning video sharing: java teaching video)
What is a thread pool?
Thread pool is a form of multi-thread processing. During the processing, tasks are submitted to the thread pool, and the execution of the task is managed by the thread pool.
If each request creates a thread to process, the server's resources will soon be exhausted. Using a thread pool can reduce the number of threads created and destroyed, and each worker thread can be reused. , can perform multiple tasks.
Why use thread pool?
The cost of creating and destroying threads is relatively large, and these times may be longer than the time of processing business. Such frequent creation and destruction of threads, coupled with business worker threads, consume system resource time, which may lead to insufficient system resources. (We can remove the process of creating and destroying threads)
What is the role of the thread pool?
The function of the thread pool is to limit the number of execution threads in the system.
1. Improve efficiency. Create a certain number of threads and put them in the pool, and take one from the pool when needed. This is much faster than creating a thread object when needed.
2. To facilitate management, you can write thread pool management code to manage the threads in the pool uniformly. For example, the program creates 100 threads when it is started. Whenever there is a request, a thread is assigned to work. , if there happen to be 101 concurrent requests, the extra request can be queued to avoid system crashes caused by endless thread creation.
Let’s talk about several common thread pools and usage scenarios
1. newSingleThreadExecutor
Create a single-threaded thread pool, which will only use the only working thread. Execute tasks to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).
2. newFixedThreadPool
Create a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeding threads will wait in the queue.
3. newCachedThreadPool
Create a cacheable thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled. If there is no recycling, create a new thread.
4. newScheduledThreadPool
Create a fixed-length thread pool to support scheduled and periodic task execution.
Several important parameters in the thread pool
corePoolSize is the number of core threads in the thread pool. These core threads will not be recycled only when they are no longer useful
maximumPoolSize is the maximum number of threads that can be accommodated in the thread pool
keepAliveTime is the longest time that other threads other than core threads can be retained in the thread pool, because in the thread pool, Except for core threads that cannot be cleared even when there are no tasks, the rest have a survival time, which means the longest idle time that non-core threads can retain
util is used to calculate this time one unit.
workQueue is a waiting queue. Tasks can be stored in the task queue waiting to be executed. The FIFIO principle (first in, first out) is implemented.
(More related interview question sharing: java interview questions and answers)
threadFactory is a thread factory that creates threads.
handler is a rejection strategy. We can refuse to perform certain tasks after the tasks are full.
Talk about the denial strategy of the thread pool
When request tasks continue to come and the system cannot handle them at this time, the strategy we need to adopt is to deny service. The RejectedExecutionHandler interface provides the opportunity for custom methods of rejecting task processing. Four processing strategies have been included in ThreadPoolExecutor.
AbortPolicy strategy: This strategy will directly throw an exception and prevent the system from working normally.
CallerRunsPolicy strategy: As long as the thread pool is not closed, this strategy runs the current discarded task directly in the caller thread.
DiscardOleddestPolicy strategy: This strategy will discard the oldest request, which is the task that is about to be executed, and try to submit the current task again.
DiscardPolicy strategy: This strategy silently discards tasks that cannot be processed without any processing.
In addition to the four rejection strategies provided by JDK by default, we can customize the rejection strategy according to our own business needs. The customization method is very simple, just implement the RejectedExecutionHandler interface directly.
What is the difference between execute and submit?
In the previous explanation, we used the execute method to execute tasks. In addition to the execute method, there is also a submit method that can also execute the tasks we submitted.
What is the difference between these two methods? In what scenarios are they applicable? Let's do a simple analysis.
execute is suitable for scenarios where you do not need to pay attention to the return value. You only need to throw the thread into the thread pool for execution.
The submit method is suitable for scenarios where you need to pay attention to the return value
Usage scenarios of five thread pools
newSingleThreadExecutor: A single-threaded thread pool that can be used in scenarios where sequential execution needs to be guaranteed, and only one thread is executing.
newFixedThreadPool: A fixed-size thread pool that can be used to limit the number of threads under known concurrency pressure.
newCachedThreadPool: A thread pool that can be expanded infinitely, which is more suitable for processing tasks with relatively small execution time.
newScheduledThreadPool: A thread pool that can be started with delay and scheduled, suitable for scenarios that require multiple background threads to perform periodic tasks.
newWorkStealingPool: A thread pool with multiple task queues, which can reduce the number of connections and create threads with the current number of available CPUs for parallel execution.
Close the thread pool
Closing the thread pool can be achieved by calling shutdownNow and shutdown methods
shutdownNow: issue interrupt() to all executing tasks and stop execution , cancel all tasks that have not yet started, and return the list of tasks that have not yet started.
shutdown: When we call shutdown, the thread pool will no longer accept new tasks, but it will not forcefully terminate tasks that have been submitted or are being executed.
Selection of the number of threads when initializing the thread pool
If the task is IO-intensive, generally the number of threads needs to be set to more than 2 times the number of CPUs to maximize the use of CPU resources.
If the task is CPU-intensive, generally the number of threads only needs to be set by adding 1 to the number of CPUs. More threads can only increase context switching but cannot increase CPU utilization.
The above is just a basic idea. If you really need precise control, you still need to observe the number of threads and queues in the thread pool after going online.
What kind of work queues are there in the thread pool?
1. ArrayBlockingQueue
is a bounded blocking queue based on an array structure. This queue is based on FIFO (first in first out) Principles to sort elements.
2. LinkedBlockingQueue
A blocking queue based on a linked list structure. This queue sorts elements according to FIFO (first in first out), and the throughput is usually higher than ArrayBlockingQueue. The static factory method Executors.newFixedThreadPool() uses this queue
3, SynchronousQueue
a blocking queue that does not store elements. Each insertion operation must wait until another thread calls the removal operation, otherwise the insertion operation will always be blocked, and the throughput is usually higher than the LinkedBlockingQueue. The static factory method Executors.newCachedThreadPool uses this queue.
4. PriorityBlockingQueue
An infinite blocking queue with priority.
Related course recommendations: java introductory tutorial
The above is the detailed content of Java interview thread pool. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
What is a deadlock in Java and how can you prevent it?
Aug 23, 2025 pm 12:55 PM
AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree
How to use Optional in Java?
Aug 22, 2025 am 10:27 AM
UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor
Java Persistence with Spring Data JPA and Hibernate
Aug 22, 2025 am 07:52 AM
The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona
Java Cryptography Architecture (JCA) for Secure Coding
Aug 23, 2025 pm 01:20 PM
Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time
LOL Game Settings Not Saving After Closing [FIXED]
Aug 24, 2025 am 03:17 AM
IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.
How to use the Pattern and Matcher classes in Java?
Aug 22, 2025 am 09:57 AM
The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient
Edit bookmarks in chrome
Aug 27, 2025 am 12:03 AM
Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.
'Java is not recognized' Error in CMD [3 Simple Steps]
Aug 23, 2025 am 01:50 AM
IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.


