都在建議你不要直接使用 @Async 注解,為什么?
點(diǎn)擊上方“碼農(nóng)突圍”,馬上關(guān)注
這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包 真愛(ài),請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看

@Async注解,在Spring體系中的應(yīng)用。本文僅說(shuō)明@Async注解的應(yīng)用規(guī)則,對(duì)于原理,調(diào)用邏輯,源碼分析,暫不介紹。對(duì)于異步方法調(diào)用,從Spring3開(kāi)始提供了@Async注解,該注解可以被標(biāo)注在方法上,以便異步地調(diào)用該方法。調(diào)用者將在調(diào)用時(shí)立即返回,方法的實(shí)際執(zhí)行將提交給Spring TaskExecutor的任務(wù)中,由指定的線程池中的線程執(zhí)行。@Async調(diào)用線程池,推薦使用自定義線程池的模式。自定義線程池常用方案:重新實(shí)現(xiàn)接口AsyncConfigurer。| 簡(jiǎn)介
應(yīng)用場(chǎng)景
SimpleAsyncTaskExecutor:不是真的線程池,這個(gè)類不重用線程,默認(rèn)每次調(diào)用都會(huì)創(chuàng)建一個(gè)新的線程。SyncTaskExecutor:這個(gè)類沒(méi)有實(shí)現(xiàn)異步調(diào)用,只是一個(gè)同步操作。只適用于不需要多線程的地方。ConcurrentTaskExecutor:Executor的適配類,不推薦使用。如果ThreadPoolTaskExecutor不滿足要求時(shí),才用考慮使用這個(gè)類。SimpleThreadPoolTaskExecutor:是Quartz的SimpleThreadPool的類。線程池同時(shí)被quartz和非quartz使用,才需要使用此類。ThreadPoolTaskExecutor:最常使用,推薦。其實(shí)質(zhì)是對(duì)java.util.concurrent.ThreadPoolExecutor的包裝。
異步的方法有:
最簡(jiǎn)單的異步調(diào)用,返回值為void。
帶參數(shù)的異步調(diào)用,異步方法可以傳入?yún)?shù)。
存在返回值,常調(diào)用返回Future。
| Spring中啟用@Async
// 基于Java配置的啟用方式:
@Configuration
@EnableAsync
public class SpringAsyncConfig { ... }
// Spring boot啟用:
@EnableAsync
@EnableTransactionManagement
public class SettlementApplication {
public static void main(String[] args) {
SpringApplication.run(SettlementApplication.class, args);
}
}
| @Async應(yīng)用默認(rèn)線程池
@Async注解在使用時(shí),不指定線程池的名稱。查看源碼,@Async的默認(rèn)線程池為SimpleAsyncTaskExecutor。@Async無(wú)返回值調(diào)用,直接在使用類,使用方法(建議在使用方法)上,加上注解。若需要拋出異常,需手動(dòng)new一個(gè)異常拋出。/**
* 帶參數(shù)的異步調(diào)用 異步方法可以傳入?yún)?shù)
* 對(duì)于返回值是void,異常會(huì)被AsyncUncaughtExceptionHandler處理掉
* @param s
*/
@Async
public void asyncInvokeWithException(String s) {
log.info("asyncInvokeWithParameter, parementer={}", s);
throw new IllegalArgumentException(s);
}
/**
* 異常調(diào)用返回Future
* 對(duì)于返回值是Future,不會(huì)被AsyncUncaughtExceptionHandler處理,需要我們?cè)诜椒ㄖ胁东@異常并處理
* 或者在調(diào)用方在調(diào)用Futrue.get時(shí)捕獲異常進(jìn)行處理
*
* @param i
* @return
*/
@Async
public Future<String> asyncInvokeReturnFuture(int i) {
log.info("asyncInvokeReturnFuture, parementer={}", i);
Future<String> future;
try {
Thread.sleep(1000 * 1);
future = new AsyncResult<String>("success:" + i);
throw new IllegalArgumentException("a");
} catch (InterruptedException e) {
future = new AsyncResult<String>("error");
} catch(IllegalArgumentException e){
future = new AsyncResult<String>("error-IllegalArgumentException");
}
return future;
}
CompletionStage代表異步計(jì)算過(guò)程中的某一個(gè)階段,一個(gè)階段完成以后可能會(huì)觸發(fā)另外一個(gè)階段 一個(gè)階段的計(jì)算執(zhí)行可以是一個(gè)Function,Consumer或者Runnable。比如: stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.println())。一個(gè)階段的執(zhí)行可能是被單個(gè)階段的完成觸發(fā),也可能是由多個(gè)階段一起觸發(fā)。
它可能代表一個(gè)明確完成的Future,也有可能代表一個(gè)完成階段( CompletionStage ),它支持在計(jì)算完成以后觸發(fā)一些函數(shù)或執(zhí)行某些動(dòng)作。 它實(shí)現(xiàn)了Future和CompletionStage接口。
/**
* 數(shù)據(jù)查詢線程池
*/
private static final ThreadPoolExecutor SELECT_POOL_EXECUTOR = new ThreadPoolExecutor(10, 20, 5000,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("selectThreadPoolExecutor-%d").build());
// tradeMapper.countTradeLog(tradeSearchBean)方法表示,獲取數(shù)量,返回值為int
// 獲取總條數(shù)
CompletableFuture<Integer> countFuture = CompletableFuture
.supplyAsync(() -> tradeMapper.countTradeLog(tradeSearchBean), SELECT_POOL_EXECUTOR);
// 同步阻塞
CompletableFuture.allOf(countFuture).join();
// 獲取結(jié)果
int count = countFuture.get();
newFixedThreadPool和newSingleThreadExecutor:主要問(wèn)題是堆積的請(qǐng)求處理隊(duì)列可能會(huì)耗費(fèi)非常大的內(nèi)存,甚至OOM。 newCachedThreadPool和newScheduledThreadPool:要問(wèn)題是線程數(shù)最大數(shù)是 Integer.MAX_VALUE,可能會(huì)創(chuàng)建數(shù)量非常多的線程,甚至OOM。
concurrencyLimit>=0時(shí)開(kāi)啟限流機(jī)制,默認(rèn)關(guān)閉限流機(jī)制即concurrencyLimit=-1,當(dāng)關(guān)閉情況下,會(huì)不斷創(chuàng)建新的線程來(lái)處理任務(wù)?;谀J(rèn)配置,SimpleAsyncTaskExecutor并不是嚴(yán)格意義的線程池,達(dá)不到線程復(fù)用的功能。| @Async應(yīng)用自定義線程池
重新實(shí)現(xiàn)接口AsyncConfigurer; 繼承AsyncConfigurerSupport; 配置由自定義的TaskExecutor替代內(nèi)置的任務(wù)執(zhí)行器。
@Async的默認(rèn)調(diào)用規(guī)則,會(huì)優(yōu)先查詢?cè)创a中實(shí)現(xiàn)AsyncConfigurer這個(gè)接口的類,實(shí)現(xiàn)這個(gè)接口的類為AsyncConfigurerSupport。但默認(rèn)配置的線程池和異步處理方法均為空,所以,無(wú)論是繼承或者重新實(shí)現(xiàn)接口,都需指定一個(gè)線程池。且重新實(shí)現(xiàn) public Executor getAsyncExecutor()方法。@Configuration
public class AsyncConfiguration implements AsyncConfigurer {
@Bean("kingAsyncExecutor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
int corePoolSize = 10;
executor.setCorePoolSize(corePoolSize);
int maxPoolSize = 50;
executor.setMaxPoolSize(maxPoolSize);
int queueCapacity = 10;
executor.setQueueCapacity(queueCapacity);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
String threadNamePrefix = "kingDeeAsyncExecutor-";
executor.setThreadNamePrefix(threadNamePrefix);
executor.setWaitForTasksToCompleteOnShutdown(true);
// 使用自定義的跨線程的請(qǐng)求級(jí)別線程工廠類19 int awaitTerminationSeconds = 5;
executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return executor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> ErrorLogger.getInstance().log(String.format("執(zhí)行異步任務(wù)'%s'", method), ex);
}
}
@Configuration
@EnableAsync
class SpringAsyncConfigurer extends AsyncConfigurerSupport {
@Bean
public ThreadPoolTaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(3);
threadPool.setMaxPoolSize(3);
threadPool.setWaitForTasksToCompleteOnShutdown(true);
threadPool.setAwaitTerminationSeconds(60 * 15);
return threadPool;
}
@Override
public Executor getAsyncExecutor() {
return asyncExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> ErrorLogger.getInstance().log(String.format("執(zhí)行異步任務(wù)'%s'", method), ex);
}
}
beanFactory.getBean(TaskExecutor.class)先查看是否有線程池,未配置時(shí),通過(guò)beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class),又查詢是否存在默認(rèn)名稱為TaskExecutor的線程池。所以可以在項(xiàng)目中,定義名稱為TaskExecutor的bean生成一個(gè)默認(rèn)線程池。也可不指定線程池的名稱,申明一個(gè)線程池,本身底層是基于TaskExecutor.class便可。比如:Executor.class:ThreadPoolExecutorAdapter->ThreadPoolExecutor->AbstractExecutorService->ExecutorService->Executor
Executor.class,在替換默認(rèn)的線程池時(shí),需設(shè)置默認(rèn)的線程池名稱為TaskExecutor。TaskExecutor.class:ThreadPoolTaskExecutor->SchedulingTaskExecutor->AsyncTaskExecutor->TaskExecutor
TaskExecutor.class,在替換默認(rèn)的線程池時(shí),可不指定線程池名稱。@EnableAsync
@Configuration
public class TaskPoolConfig {
@Bean(name = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心線程池大小
executor.setCorePoolSize(10);
//最大線程數(shù)
executor.setMaxPoolSize(20);
//隊(duì)列容量
executor.setQueueCapacity(200);
//活躍時(shí)間
executor.setKeepAliveSeconds(60);
//線程名字前綴
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
@Bean(name = "new_task")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心線程池大小
executor.setCorePoolSize(10);
//最大線程數(shù)
executor.setMaxPoolSize(20);
//隊(duì)列容量
executor.setQueueCapacity(200);
//活躍時(shí)間
executor.setKeepAliveSeconds(60);
//線程名字前綴
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
@Async注解,使用系統(tǒng)默認(rèn)或者自定義的線程池(代替默認(rèn)線程池)??稍陧?xiàng)目中設(shè)置多個(gè)線程池,在異步調(diào)用時(shí),指明需要調(diào)用的線程池名稱,如@Async("new_task")。| @Async部分重要源碼解析

getAsyncExecutor()時(shí),可以設(shè)置默認(rèn)的線程池。



-End-
最近有一些小伙伴,讓我?guī)兔φ乙恍?nbsp;面試題 資料,于是我翻遍了收藏的 5T 資料后,匯總整理出來(lái),可以說(shuō)是程序員面試必備!所有資料都整理到網(wǎng)盤了,歡迎下載!
點(diǎn)擊??卡片,關(guān)注后回復(fù)【面試題】即可獲取
評(píng)論
圖片
表情

