Created
February 19, 2015 21:55
-
-
Save jbrisbin/e4b82919329a28ef6c9c to your computer and use it in GitHub Desktop.
Demo class for calculating Pi using Reactor
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
import org.apache.commons.lang.time.StopWatch; | |
import reactor.Environment; | |
import reactor.fn.BiFunction; | |
import reactor.rx.Streams; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* Demo class for calculating Pi using Reactor. | |
*/ | |
public class ReactorDispatchingExample { | |
static { | |
Environment.initializeIfEmpty().assignErrorJournal(); | |
} | |
public static void main(String... args) throws InterruptedException { | |
int iterations = 25000000; | |
StopWatch watch = new StopWatch(); | |
watch.start(); | |
double pi = Streams | |
.range(1, iterations) | |
.dispatchOn(Environment.sharedDispatcher()) | |
.capacity(16 * 1024) | |
.filter(i -> (i == 1 || i % 2 != 0)) | |
.map(i -> (double) 4 / i) | |
.reduce(new PiReducer()) | |
.next() | |
.await(30, TimeUnit.SECONDS); | |
watch.stop(); | |
double throughput = iterations / (double) (watch.getTime() / 1000); | |
System.out.println("pi calculated to " + pi + " / throughput: " + (long) throughput + " ops/s"); | |
} | |
static final class PiReducer implements BiFunction<Double, Double, Double> { | |
boolean subtract; | |
@Override | |
public Double apply(Double prev, Double next) { | |
return ((subtract ^= true) ? prev - next : prev + next); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment