{"id":329573,"date":"2024-05-22T19:40:00","date_gmt":"2024-05-22T19:40:00","guid":{"rendered":"https:\/\/www.baeldung.com\/completablefuture-vs-mono"},"modified":"2024-05-22T19:40:00","modified_gmt":"2024-05-22T19:40:00","slug":"completablefuture-vs-mono","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2024\/05\/22\/completablefuture-vs-mono\/","title":{"rendered":"CompletableFuture vs. Mono"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" style=\"float: left; margin-right: 5px;\" decoding=\"async\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg 952w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2-300x157.jpg 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2-768x402.jpg 768w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2  class=\"\" id=\"bd-1-overview\" data-id=\"1-overview\">1. Overview<\/h2>\n<div class=\"bd-anchor\" id=\"1-overview\"><\/div>\n<p class=\"\">In this quick tutorial, we&#8217;ll learn the differences between <em>CompletableFuture<\/em> and <em>Mono<\/em> from Project Reactor in Java. We&#8217;ll focus on how they handle asynchronous tasks and the execution that occurs to accomplish those tasks.<\/p>\n<p>Let&#8217;s start by looking at <em>CompletableFuture<\/em>.<\/p>\n<h2  class=\"\" id=\"bd-2-understanding-completablefuture\" data-id=\"2-understanding-completablefuture\">2. Understanding <em>CompletableFuture<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"2-understanding-completablefuture\"><\/div>\n<p class=\"\">Introduced in Java 8,\u00a0<em><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-completablefuture\">CompletableFuture<\/a><\/em>\u00a0builds upon the previous <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-future\"><em>Future<\/em><\/a> class and provides a way to run code asynchronously. In short, it improves asynchronous programming and simplifies working with threads.<\/p>\n<p class=\"\">Moreover, we can create a chain of computations with methods like <em><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-completablefuture#1-thenapply\">thenApply()<\/a><\/em>, <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/concurrent\/CompletableFuture.html#thenAccept-java.util.function.Consumer-\"><em>thenAccept()<\/em><\/a>, and\u00a0<em><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-completablefuture#1-thenapply\">thenCompose()<\/a><\/em>\u00a0to coordinate our asynchronous tasks.<\/p>\n<p class=\"\">While <em>CompletableFuture<\/em> is asynchronous, meaning the main thread continues executing other tasks without waiting for the completion of the current operation, <strong>it isn&#8217;t fully non-blocking<\/strong>. A long-running operation can block the thread executing it:<\/p>\n<pre class=\"language-java Java\"><code>CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -&gt; {\r\n    try {\r\n        Thread.sleep(1000);\r\n    } catch (InterruptedException e) {\r\n        Thread.currentThread().interrupt();\r\n    }\r\n    return &quot;Finished completableFuture&quot;;\r\n});\r\n<\/code><\/pre>\n<p>Above, we&#8217;re simulating a long operation with the <em>sleep()<\/em> method from the <em>Thread<\/em> class. If not defined, <em>supplyAsnc()<\/em> will use <em>ForkJoinPool<\/em> and assign a thread to run the anonymous <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-8-functional-interfaces#Lambdas\">lambda function<\/a>, and this thread gets blocked by the <em>sleep()<\/em> method.<\/p>\n<p>Moreover, <strong>calling the <em>get()<\/em> method in the <em>CompletableFuture<\/em> instance before it completes the operation blocks the main thread<\/strong>:<\/p>\n<pre><code class=\"language-java\">try {\r\n    completableFuture.get(); \/\/ This blocks the main thread\r\n} catch (InterruptedException | ExecutionException e) {\r\n    e.printStackTrace();\r\n}<\/code><\/pre>\n<p>To avoid such occurrences, we can handle the <em>CompletableFuture<\/em> completion manually using the <em>completeExceptionally()<\/em> or <em>complete()<\/em> methods in the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-callback-functions\">callback pattern<\/a>. For example, suppose we have a function that we want to run without blocking the main thread, and then, we want to handle the future when it fails and when it completes successfully:<\/p>\n<pre class=\"language-java Java\"><code>public void myAsyncCall(String param, BiConsumer&lt;String, Throwable&gt; callback) {\r\n    new Thread(() -&gt; {\r\n        try {\r\n            Thread.sleep(1000);\r\n            callback.accept(&quot;Response from API with param: &quot; + param, null);\r\n        } catch (InterruptedException e) {\r\n            callback.accept(null, e);\r\n        }\r\n    }).start();\r\n}\r\n<\/code><\/pre>\n<p>Then, we use this function to create a <em>CompletableFuture<\/em>:<\/p>\n<pre class=\"language-java Java\"><code>public CompletableFuture&lt;String&gt; nonBlockingApiCall(String param) {\r\n    CompletableFuture&lt;String&gt; completableFuture = new CompletableFuture&lt;&gt;();\r\n    myAsyncCall(param, (result, error) -&gt; {\r\n        if (error != null) {\r\n            completableFuture.completeExceptionally(error);\r\n        } else {\r\n            completableFuture.complete(result);\r\n        }\r\n    });\r\n    return completableFuture;\r\n}\r\n<\/code><\/pre>\n<p>There&#8217;s an alternative and a more reactive way to handle the same operation, as we&#8217;ll see next.<\/p>\n<h2  id=\"bd-3-understanding-mono\" data-id=\"3-understanding-mono\">3. Comparing <em>Mono<\/em> With <em>CompletableFuture<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"3-understanding-mono\"><\/div>\n<p>The <em>Mono<\/em> class from <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/reactor-core\">Project Reactor<\/a>\u00a0uses reactive principles. Unlike <em>CompletableFuture<\/em>, <strong><em>Mono<\/em> is designed to be non-blocking and to support concurrency with less overhead<\/strong>.<\/p>\n<p>Additionally, <em>Mono<\/em> is lazy compared to the eager execution of the <em>CompletableFuture<\/em>, meaning that our application won&#8217;t consume resources unless we subscribe to <em>Mono<\/em>:<\/p>\n<pre class=\"language-java Java\"><code>Mono&lt;String&gt; reactiveMono = Mono.fromCallable(() -&gt; {\r\n    Thread.sleep(1000); \/\/ Simulate some computation\r\n    return &quot;Reactive Data&quot;;\r\n}).subscribeOn(Schedulers.boundedElastic());\r\nreactiveMono.subscribe(System.out::println);\r\n<\/code><\/pre>\n<p class=\"\">Above, we&#8217;re creating a <em>Mono<\/em> object using the <em>fromCallable()<\/em> method and providing the blocking operation as a <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-callable-vs-supplier#supplier\">supplier<\/a>. Then, we delegate the operation, using the <em>subscribeOn()<\/em> method, to a separate thread.<\/p>\n<p class=\"\"><strong><em>Schedulers.boundedElastic()<\/em>\u00a0is similar to a cached thread pool but with a limit on the maximum number of threads<\/strong>. This ensures the main thread remains non-blocking. The only way to block the main thread is forcefully call the <em>block()<\/em> method. This method waits for the completion, successful or not, of the <em>Mono<\/em> instance.<\/p>\n<p class=\"\">Then, to run the reactive pipeline, we use <em>subscribe()<\/em> to subscribe the outcome of the <em>Mono<\/em> object to <em>println()<\/em> using <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-method-references\">method reference<\/a>.<\/p>\n<p>The <em>Mono<\/em> class is very flexible and provides a set of operators to transform and combine other <em>Mono<\/em> objects descriptively. It also supports <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/spring-webflux-backpressure#backpressure-in-reactive-streams\">backpressure<\/a> to prevent the application from eating up all the resources.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">4. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this quick article, we compared <em>CompletableFuture<\/em> with the <em>Mono<\/em> class from Project Reactor. First, we described how <em>CompletableFuture<\/em> can run an asynchronous task. Then, we showed that, if configured incorrectly, it can block the thread it&#8217;s working on as well as the main thread. Finally, we showed how to run an asynchronous operation in a reactive way using <em>Mono<\/em>.<\/p>\n<p>As always, we can find the complete code <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/reactor-core-2\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/897312110\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897312110\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2016%2F10%2Fsocial-Java-On-Baeldung-2.jpg\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-completablefuture-mono-differences#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-completablefuture-mono-differences\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2016\/10\/social-Java-On-Baeldung-2.jpg\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\"><\/p>\n<p>In this quick tutorial, we&#8217;ll compare CompletableFuture and Mono from Project Reactor in Java, focusing on how they handle asynchronous tasks.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897312110\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2016%2F10%2Fsocial-Java-On-Baeldung-2.jpg\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897312110\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-completablefuture-mono-differences#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-completablefuture-mono-differences\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n<\/div>","protected":false},"author":2058,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"CompletableFuture vs. Mono - ITTeacherITFreelance.hk","description":"In this quick tutorial, we'll compare CompletableFuture and Mono from Project Reactor in Java, focusing on how they handle asynchronous tasks. \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0"},"footnotes":""},"categories":[6,1307],"tags":[10805],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329573"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/2058"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=329573"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329573\/revisions"}],"predecessor-version":[{"id":329574,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329573\/revisions\/329574"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=329573"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=329573"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=329573"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}