Last active
April 4, 2018 07:09
-
-
Save adamw/4866c20270c949e57593d64496afd444 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.concurrent.*; | |
import java.util.concurrent.atomic.AtomicReference; | |
/* | |
* Let's say we want to fetch the user's profile from one API call, | |
* and the user's friends from another API call, in parallel. | |
*/ | |
public class Compare2Synchronous { | |
// I/0 operations: blocking, synchronous | |
String sendHttpGet(String url) { return null; } | |
// the business logic: manual, explicit concurrency | |
// accepting the executor as a parameter, so that it can be shared | |
String runBusinessProcess(ExecutorService executor, long userId) throws InterruptedException { | |
// the atomic references will store the results of both API calls | |
AtomicReference<String> profileResult = new AtomicReference<String>(null); | |
AtomicReference<String> friendsResult = new AtomicReference<String>(null); | |
// the latch will reach 0 once both API calls complete | |
CountDownLatch done = new CountDownLatch(2); | |
// submitting tasks to send the API calls. If the executor has enough threads, | |
// these will run in parallel | |
executor.execute(() -> { | |
String result = sendHttpGet("http://profile_service/get/" + userId); | |
profileResult.set(result); | |
done.countDown(); | |
}); | |
executor.execute(() -> { | |
String result = sendHttpGet("http://friends_service/get/" + userId); | |
friendsResult.set(result); | |
done.countDown(); | |
}); | |
// in the main thread, waiting until both computations are done | |
done.await(); | |
return "Profile: " + profileResult.get() + ", friends: " + friendsResult.get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment