簡體   English   中英

Spring Boot +多線程+處理連接池

[英]Spring Boot + multi threading + handling connection pool

我有一個Spring-boot應用程序,其中包含以下內容:
1. REST-API
2.從開始運行的一個線程將執行一個服務BS (我們可以說后台服務)

注意BS有代碼來創建10個子線程,它以異步方式運行以完成任務。

要求
1. BS是獨立的線程,它將在主線程的整個應用程序中運行。
2. Child thread :將在BS創建,一旦完成,將在BS折疊。

問題 :如果沒有待處理的工作,我的線程BS需要休眠(或者你可以說處於wait狀態)並在工作結束時返回( notify )。 為此,我使用傳統方式wait...notify但是在等待BS線程時, 10個子線程正在執行BS線程正在執行的相同代碼。 我認為線程池管理沒有得到妥善處理。
幫助欣賞

BS ThreadThreadPoolTask​​ExecutorCommandLineRunner ,連接池設置為1

 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
    executor.setCorePoolSize(1);  
    executor.setMaxPoolSize(1);  
    executor.setQueueCapacity(500);  
    executor.setThreadNamePrefix("BS Thread:");  
    executor.initialize();  
    return executor;   

Child Thread :使用以下代碼創建10個線程:

 ExecutorService service = Executors.newFixedThreadPool(10);
 for (BSChildExecutor jobs : listOfJobs) {
     service.submit(jobs);
 }  
 service.shutdown();`    

我認為你的設計存在缺陷。 您想要實現的流程可以非常簡化。

首先,你已經添加了根本不需要的BS 典型的BS是流程,包括日志記錄,系統監控,調度,通知等。

在您的情況下, BS本身就是由線程池提供的。

創建一個X大小的線程池,它滿足您的要求,在您正常關閉Spring應用程序之前永遠不會消亡。 由於REST API是執行listOfJobs的觸發點,因此每當新作業到來時,您都會繼續提交到池中。

在正常關閉Spring應用程序的同時正常關閉線程池的代碼段

public void onApplicationEvent(ContextClosedEvent event) {
        this.connector.pause();
        Executor executor = this.connector.getProtocolHandler().getExecutor();
        if (executor instanceof ThreadPoolExecutor) {
            try {
                ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
                threadPoolExecutor.shutdown();
                if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                    log.warn("Thread pool did not shut down gracefully within "
                            + TIMEOUT + " seconds. Proceeding with forceful shutdown");

                    threadPoolExecutor.shutdownNow();

                    if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                        log.error("Thread pool did not terminate");
                    }
                }
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM