{"id":21699542,"url":"https://github.com/emahtab/completable-future","last_synced_at":"2025-03-20T15:40:59.942Z","repository":{"id":262847835,"uuid":"888551829","full_name":"eMahtab/completable-future","owner":"eMahtab","description":"Java 8 CompletableFuture","archived":false,"fork":false,"pushed_at":"2024-11-14T16:43:21.000Z","size":20,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-25T14:42:36.489Z","etag":null,"topics":["completable-future","concurrency","java-8"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-14T15:40:08.000Z","updated_at":"2024-11-14T16:43:25.000Z","dependencies_parsed_at":"2024-11-14T16:38:53.619Z","dependency_job_id":"d7d537d8-4896-4424-a04b-68145b3a69a4","html_url":"https://github.com/eMahtab/completable-future","commit_stats":null,"previous_names":["emahtab/completable-future"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fcompletable-future","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fcompletable-future/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fcompletable-future/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fcompletable-future/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/completable-future/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244643637,"owners_count":20486660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["completable-future","concurrency","java-8"],"created_at":"2024-11-25T20:10:02.517Z","updated_at":"2025-03-20T15:40:59.918Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# CompletableFuture\nA Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.\n**CompletableFuture class was introduced with Java 1.8**\n\n\n#### Example 1 : Combining the result of two async operations (CompletableFuture), thenAccept() non-blocking\n```java\nimport java.util.concurrent.CompletableFuture;\n\npublic class CompletableFutureExample {\n\t\n    public static void main(String[] args) {\n        // Start both tasks asynchronously\n        CompletableFuture\u003cString\u003e userFuture = CompletableFuture.supplyAsync(() -\u003e {\n            try { // Simulate an API call to fetch user data\n            \tSystem.out.println(\"userFuture being executed by :\"+Thread.currentThread().getName());\n                Thread.sleep(2000); // Simulate network delay\n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n            return \"User Data: John Doe\";\n        });\n        CompletableFuture\u003cString\u003e orderFuture = CompletableFuture.supplyAsync(() -\u003e {\n            try { // Simulate an API call to fetch user orders\n            \tSystem.out.println(\"orderFuture being executed by :\"+Thread.currentThread().getName());\n                Thread.sleep(3000); // Simulate network delay\n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n            return \"Order Data: [Order1, Order2, Order3]\";\n        });\n\n        // Combine the results of both tasks\n        CompletableFuture\u003cString\u003e combinedFuture = userFuture.thenCombine(orderFuture, (userData, orderData) -\u003e {\n            return userData + \", \" + orderData;\n        });\n\n        // Print the combined result\n        System.out.println(\"Fetching data asynchronously...\");\n        combinedFuture.thenAccept(result -\u003e {\n           System.out.println(\"Result: \" + result);\n        });\n        System.out.println(\"Running the code in main thread\");\n        try {\n        \tThread.sleep(10000); // this delay so that main thread don't finish and get destroyed before we receive result of async operations\n        }catch(InterruptedException exp) {\n        \texp.printStackTrace();\n        }\n        System.out.println(\"main method finished executing\");\n    }\n}\n```\n\n### Code Execution Output\n```\norderFuture being executed by :ForkJoinPool.commonPool-worker-2\nFetching data asynchronously...\nuserFuture being executed by :ForkJoinPool.commonPool-worker-1\nRunning the code in main thread\nResult: User Data: John Doe, Order Data: [Order1, Order2, Order3]\nmain method finished executing\n```\n\n#### Example 2 : Combining the result of two async operations (CompletableFuture), get() blocking\n```java\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\n\npublic class CompletableFutureExample {\n\t\n    public static void main(String[] args) {\n        // Start both tasks asynchronously\n        CompletableFuture\u003cString\u003e userFuture = CompletableFuture.supplyAsync(() -\u003e {\n            try { // Simulate an API call to fetch user data\n            \tSystem.out.println(\"userFuture being executed by :\"+Thread.currentThread().getName());\n                Thread.sleep(2000); // Simulate network delay\n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n            return \"User Data: John Doe\";\n        });\n        CompletableFuture\u003cString\u003e orderFuture = CompletableFuture.supplyAsync(() -\u003e {\n            try { // Simulate an API call to fetch user orders\n            \tSystem.out.println(\"orderFuture being executed by :\"+Thread.currentThread().getName());\n                Thread.sleep(3000); // Simulate network delay\n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n            return \"Order Data: [Order1, Order2, Order3]\";\n        });\n\n        // Combine the results of both tasks\n        CompletableFuture\u003cString\u003e combinedFuture = userFuture.thenCombine(orderFuture, (userData, orderData) -\u003e {\n            return userData + \", \" + orderData;\n        });\n\n        // Print the combined result\n        System.out.println(\"Fetching data asynchronously...\");\n        try {\n              System.out.println(\"Result: \" + combinedFuture.get());\n        } catch (InterruptedException | ExecutionException e) {\n              e.printStackTrace();\n        }\n        System.out.println(\"main method finished executing\");\n    }\n}\n```\n### Code Execution Output\n```\nFetching data asynchronously...\nuserFuture being executed by :ForkJoinPool.commonPool-worker-1\norderFuture being executed by :ForkJoinPool.commonPool-worker-2\nResult: User Data: John Doe, Order Data: [Order1, Order2, Order3]\nmain method finished executing\n```\n\n### Example 3 : Chaining operations on CompletableFuture\n```java\nimport java.util.concurrent.CompletableFuture;\npublic class CompletableFutureExample {\n\tpublic static void main(String[] args) {\n\t\tCompletableFuture\u003cString\u003e future = CompletableFuture.supplyAsync(() -\u003e \"Hello\")\n\t\t        .thenApply(result -\u003e result + \" World\")\n\t\t        .thenApply(result -\u003e result.toUpperCase());\n\n\t\tfuture.thenAccept((result) -\u003e System.out.println(\"Result :\"+result)); // Output: HELLO WORLD\n\t\ttry {\n\t\t\tThread.sleep(3000);\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.out.println(\"Main method finished executing\");\n\t}\n}\n```\n\n### Code Execution Output:\n```\nResult :HELLO WORLD\nMain method finished executing\n```\n\n### Example 4 : Waiting for all the async operations to complete using allOf and thenRun\nIf you want to wait till all of CompletableFuture instances, use **allOf()** to wait for all of them to complete.\n\n```java\nimport java.util.concurrent.CompletableFuture;\npublic class CompletableFutureExample {\n\tpublic static void main(String[] args) {\n\t\tCompletableFuture\u003cString\u003e future1 = CompletableFuture.supplyAsync(() -\u003e \"Task 1\");\n\t\tCompletableFuture\u003cString\u003e future2 = CompletableFuture.supplyAsync(() -\u003e \"Task 2\");\n\t\tCompletableFuture\u003cString\u003e future3 = CompletableFuture.supplyAsync(() -\u003e \"Task 3\");\n\n\t\tCompletableFuture\u003cVoid\u003e allFutures = CompletableFuture.allOf(future1, future2, future3);\n\n\t\tallFutures.thenRun(() -\u003e {\n\t\t    try {\n\t\t        System.out.println(future1.get());\n\t\t        System.out.println(future2.get());\n\t\t        System.out.println(future3.get());\n\t\t    } catch (Exception e) {\n\t\t        e.printStackTrace();\n\t\t    }\n\t\t});\n\t\ttry {\n\t\t\tThread.sleep(5000);\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.out.println(\"Main method finished executing\");\n\t}\n}\n```\n#### Code Execution Output :\n```\nTask 1\nTask 2\nTask 3\nMain method finished executing\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fcompletable-future","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fcompletable-future","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fcompletable-future/lists"}