使用Spring Async與僅僅自己返回CompletableFuture
相比,有什麼優勢?直接使用Spring @Async和CompleteableFuture有什麼優勢?
4
A
回答
5
您的應用程序由容器管理。由於不鼓勵你自己產生Thread
,你可以讓容器注入一個託管的Executor
。
@Service
class MyService {
@Autowired
private Executor executor;
public CompletableFuture<?> compute() {
return CompletableFuture.supplyAsync(() -> /* compute value */, executor);
}
}
2
沒有「與」兩者之間:這是互補的技術:
CompletableFuture
提供了一個方便的方法來異步計算的鏈的不同階段 - 比Spring的ListenableFuture
更多的靈活性;@Async
爲您的後臺任務和線程提供了方便的管理,爲您的執行者提供了標準的Spring配置。
但是兩者都可以合併(since Spring 4.2)。假設你希望把下面的方法進入後臺任務返回CompletableFuture
:
public String compute() {
// do something slow
return "my result";
}
你要做的:
- 如果尚未:配置具有
@EnableAsync
您的應用程序和Executor
豆 - 註釋與
@Async
- 方法包裹它的結果到
CompletableFuture.completedFuture()
@Async
public CompletableFuture<String> computeAsync() {
// do something slow - no change to this part
// note: no need to wrap your code in a lambda/method reference,
// no need to bother about executor handling
return CompletableFuture.completedFuture("my result");
}
你可能注意到了,你不必理會提交後臺任務執行人:春負責的是你。您只需將結果包裝爲完整的CompletableFuture
,以便籤名與呼叫者的期望相符。
相關問題
- 1. SVN和Apache - 有沒有什麼優勢?
- 2. reftype {}有什麼優勢?
- 3. 使用NSOutputstream有什麼優勢?
- 4. Hudson vs使用shellcript有什麼優勢?
- 5. 使用Redux比React有什麼優勢?
- 6. 使用HttpApplication比HttpApplication有什麼優勢?
- 7. 使用Python Virtualbox API有什麼優勢?
- 8. 使用POCO比DataTables有什麼優勢?
- 9. 使用SVN比CVS有什麼優勢?
- 10. 使用BaseAdapter比ArrayAdapter有什麼優勢?
- 11. 使用直接Rfc調用而不是BAPI有優勢嗎?
- 12. 使用帶有Zend_Db_Table的DataMapper與使用DataMapper直接使用數據庫適配器相比,有什麼優勢?
- 13. 什麼是ASO和BSO,使用這些的優勢是什麼
- 14. 使用MS AJAX和jQuery有什麼優勢?
- 15. 使用AWS CLI和AWS PHP SDK有什麼優勢?
- 16. Spring AMQP比RabbitMQ Java客戶端有什麼優勢嗎?
- 17. ASP.NET 3.5 Extensions Preview 2有什麼優勢?
- 18. Promises優於CPS和Continuation Functor/Monad有什麼優勢?
- 19. Web服務與直接敲擊數據庫(oracle)有什麼優勢?
- 20. 使用arrayWithCapacity比使用數組有什麼優勢?
- 21. Spring Boot的優勢
- 22. django-treebeard比django-mptt有什麼優勢?
- 23. rsh與Perl的Expect.pm有什麼優勢?
- 24. PHP對ASP.NET有什麼優勢?
- 25. DIVS比表格有什麼優勢?
- 26. git比git-svn有什麼優勢?
- 27. Digest :: SHA比Digest :: SHA1有什麼優勢?
- 28. RVM在Linux上有什麼優勢?
- 29. 有什麼優勢Laravel形式語法
- 30. 從Spring @Service Bean直接使用EntityManager有什麼缺點嗎?
也許[THIS](https://stackoverflow.com/questions/533783/why-is-spawning-threads-in-java-ee-container-discouraged)會幫助你。 – Flown
這可能在java 8之前就有意義了。但是CompletableFuture默認會派生到fork連接池中。 –
你有一個託管環境。不建議自己產生線程,但如果必須的話,可以使用'CompletableFuture'和注入的'ExecutorService',它應該由容器管理。 – Flown