|
| 1 | +/** |
| 2 | + * The MIT License |
| 3 | + * Copyright (c) 2014 Ilkka Seppälä |
| 4 | + * |
| 5 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | + * of this software and associated documentation files (the "Software"), to deal |
| 7 | + * in the Software without restriction, including without limitation the rights |
| 8 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | + * copies of the Software, and to permit persons to whom the Software is |
| 10 | + * furnished to do so, subject to the following conditions: |
| 11 | + * |
| 12 | + * The above copyright notice and this permission notice shall be included in |
| 13 | + * all copies or substantial portions of the Software. |
| 14 | + * |
| 15 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 21 | + * THE SOFTWARE. |
| 22 | + */ |
| 23 | +package com.iluwatar.promise; |
| 24 | +import java.util.Map; |
| 25 | +import java.util.concurrent.CompletableFuture; |
| 26 | +import java.util.concurrent.CountDownLatch; |
| 27 | +import java.util.concurrent.ExecutionException; |
| 28 | +import java.util.concurrent.ExecutorService; |
| 29 | +import java.util.concurrent.Executors; |
| 30 | + |
| 31 | +/** |
| 32 | + * |
| 33 | + * The Promise object is used for asynchronous computations. A Promise represents an operation |
| 34 | + * that hasn't completed yet, but is expected in the future. |
| 35 | + * |
| 36 | + * <p>A Promise represents a proxy for a value not necessarily known when the promise is created. It |
| 37 | + * allows you to associate dependent promises to an asynchronous action's eventual success value or |
| 38 | + * failure reason. This lets asynchronous methods return values like synchronous methods: instead |
| 39 | + * of the final value, the asynchronous method returns a promise of having a value at some point |
| 40 | + * in the future. |
| 41 | + * |
| 42 | + * <p>Promises provide a few advantages over callback objects: |
| 43 | + * <ul> |
| 44 | + * <li> Functional composition and error handling |
| 45 | + * <li> Prevents callback hell and provides callback aggregation |
| 46 | + * </ul> |
| 47 | + * |
| 48 | + * <p> |
| 49 | + * In this application the usage of promise is demonstrated with two examples: |
| 50 | + * <ul> |
| 51 | + * <li>Count Lines: In this example a file is downloaded and its line count is calculated. |
| 52 | + * The calculated line count is then consumed and printed on console. |
| 53 | + * <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency |
| 54 | + * character is found and printed on console. This happens via a chain of promises, we start with |
| 55 | + * a file download promise, then a promise of character frequency, then a promise of lowest frequency |
| 56 | + * character which is finally consumed and result is printed on console. |
| 57 | + * </ul> |
| 58 | + * |
| 59 | + * @see CompletableFuture |
| 60 | + */ |
| 61 | +public class App { |
| 62 | + |
| 63 | + private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/Promise/promise/README.md"; |
| 64 | + private final ExecutorService executor; |
| 65 | + private final CountDownLatch stopLatch; |
| 66 | + |
| 67 | + private App() { |
| 68 | + executor = Executors.newFixedThreadPool(2); |
| 69 | + stopLatch = new CountDownLatch(2); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Program entry point |
| 74 | + * @param args arguments |
| 75 | + * @throws InterruptedException if main thread is interrupted. |
| 76 | + * @throws ExecutionException if an execution error occurs. |
| 77 | + */ |
| 78 | + public static void main(String[] args) throws InterruptedException, ExecutionException { |
| 79 | + App app = new App(); |
| 80 | + try { |
| 81 | + app.promiseUsage(); |
| 82 | + } finally { |
| 83 | + app.stop(); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private void promiseUsage() { |
| 88 | + calculateLineCount(); |
| 89 | + |
| 90 | + calculateLowestFrequencyChar(); |
| 91 | + } |
| 92 | + |
| 93 | + /* |
| 94 | + * Calculate the lowest frequency character and when that promise is fulfilled, |
| 95 | + * consume the result in a Consumer<Character> |
| 96 | + */ |
| 97 | + private void calculateLowestFrequencyChar() { |
| 98 | + lowestFrequencyChar() |
| 99 | + .thenAccept( |
| 100 | + charFrequency -> { |
| 101 | + System.out.println("Char with lowest frequency is: " + charFrequency); |
| 102 | + taskCompleted(); |
| 103 | + } |
| 104 | + ); |
| 105 | + } |
| 106 | + |
| 107 | + /* |
| 108 | + * Calculate the line count and when that promise is fulfilled, consume the result |
| 109 | + * in a Consumer<Integer> |
| 110 | + */ |
| 111 | + private void calculateLineCount() { |
| 112 | + countLines() |
| 113 | + .thenAccept( |
| 114 | + count -> { |
| 115 | + System.out.println("Line count is: " + count); |
| 116 | + taskCompleted(); |
| 117 | + } |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + /* |
| 122 | + * Calculate the character frequency of a file and when that promise is fulfilled, |
| 123 | + * then promise to apply function to calculate lowest character frequency. |
| 124 | + */ |
| 125 | + private Promise<Character> lowestFrequencyChar() { |
| 126 | + return characterFrequency() |
| 127 | + .thenApply(Utility::lowestFrequencyChar); |
| 128 | + } |
| 129 | + |
| 130 | + /* |
| 131 | + * Download the file at DEFAULT_URL and when that promise is fulfilled, |
| 132 | + * then promise to apply function to calculate character frequency. |
| 133 | + */ |
| 134 | + private Promise<Map<Character, Integer>> characterFrequency() { |
| 135 | + return download(DEFAULT_URL) |
| 136 | + .thenApply(Utility::characterFrequency); |
| 137 | + } |
| 138 | + |
| 139 | + /* |
| 140 | + * Download the file at DEFAULT_URL and when that promise is fulfilled, |
| 141 | + * then promise to apply function to count lines in that file. |
| 142 | + */ |
| 143 | + private Promise<Integer> countLines() { |
| 144 | + return download(DEFAULT_URL) |
| 145 | + .thenApply(Utility::countLines); |
| 146 | + } |
| 147 | + |
| 148 | + /* |
| 149 | + * Return a promise to provide the local absolute path of the file downloaded in background. |
| 150 | + * This is an async method and does not wait until the file is downloaded. |
| 151 | + */ |
| 152 | + private Promise<String> download(String urlString) { |
| 153 | + Promise<String> downloadPromise = new Promise<String>() |
| 154 | + .fulfillInAsync( |
| 155 | + () -> { |
| 156 | + return Utility.downloadFile(urlString); |
| 157 | + }, executor) |
| 158 | + .onError( |
| 159 | + throwable -> { |
| 160 | + throwable.printStackTrace(); |
| 161 | + taskCompleted(); |
| 162 | + } |
| 163 | + ); |
| 164 | + |
| 165 | + return downloadPromise; |
| 166 | + } |
| 167 | + |
| 168 | + private void stop() throws InterruptedException { |
| 169 | + stopLatch.await(); |
| 170 | + executor.shutdownNow(); |
| 171 | + } |
| 172 | + |
| 173 | + private void taskCompleted() { |
| 174 | + stopLatch.countDown(); |
| 175 | + } |
| 176 | +} |
0 commit comments