Skip to content

Instantly share code, notes, and snippets.

@McPringle
Created October 26, 2016 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save McPringle/62ad1797f21bc35d85c4f5a9988fa920 to your computer and use it in GitHub Desktop.
Save McPringle/62ad1797f21bc35d85c4f5a9988fa920 to your computer and use it in GitHub Desktop.
Two working solutions for exercise one, one with Java 8 CompletableFuture and one with Java 8 Stream API.
package ch.fihlon.reactive.pricecalculator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.util.concurrent.CompletableFuture.supplyAsync;
public class CompletableFutureSolution {
private static final int NUMBER_OF_SERVICE_CALLS = 10;
private final ExecutorService pool;
private double price;
private int count;
public static void main(final String... args) {
new CompletableFutureSolution().run();
}
private CompletableFutureSolution() {
this.pool = Executors.newFixedThreadPool(3);
this.price = 0;
this.count = 0;
}
private void run() {
for (int i = 0; i < NUMBER_OF_SERVICE_CALLS; i++) {
supplyAsync(() -> new PriceService().getPrice(), this.pool).thenAcceptAsync(this::collector);
}
}
private synchronized void collector(final Double price) {
System.out.println(
String.format("Collected price '%s' from thread %s", price, Thread.currentThread().getName()));
this.price += price;
if (++this.count == NUMBER_OF_SERVICE_CALLS) {
System.out.println("The average price is: " + this.price / this.count);
System.exit(0);
}
}
}
package ch.fihlon.reactive.pricecalculator;
import java.util.HashSet;
import java.util.OptionalDouble;
import java.util.Set;
public class Java8StreamSolution {
private static final int NUMBER_OF_SERVICE_CALLS = 10;
private final Set<PriceService> services;
public static void main(final String... args) {
new Java8StreamSolution().run();
}
private Java8StreamSolution() {
this.services = new HashSet<>();
for (int i = 0; i < NUMBER_OF_SERVICE_CALLS; i++) {
this.services.add(new PriceService());
}
}
private void run() {
final OptionalDouble average = this.services.parallelStream()
.mapToDouble(PriceService::getPrice)
.peek(this::printStatus)
.average();
System.out.println("The average price is: " + average.orElseGet(null));
}
private void printStatus(final Double price) {
System.out.println(
String.format("Collected price '%s' from thread %s", price, Thread.currentThread().getName()));
}
}
package ch.fihlon.reactive.pricecalculator;
import java.util.Random;
class PriceService {
private final Random random;
PriceService() {
this.random = new Random();
}
Double getPrice() {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.random.nextInt(100_000) / 100d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment