Skip to content

Instantly share code, notes, and snippets.

@RuedigerMoeller
Last active August 29, 2015 14:07
Show Gist options
  • Save RuedigerMoeller/4a6bf58275ec09277525 to your computer and use it in GitHub Desktop.
Save RuedigerMoeller/4a6bf58275ec09277525 to your computer and use it in GitHub Desktop.
Famous Pi Bench with Kontraktor 2.0
public class KontrActorPi {
public static class PiActor extends Actor<PiActor> {
public void $calculatePiFor(int start, int nrOfElements, Adder adder) {
double acc = 0.0;
for (int i = start * nrOfElements; i <= ((start + 1) * nrOfElements - 1); i++) {
acc += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1);
}
adder.$add(acc);
}
}
public static class Adder extends Actor<Adder> {
double pi = 0;
public void $add(double d) {
pi += d;
}
public void $printPi() {
System.out.println("PI: "+pi);
}
}
// blocking utility method
static long calcPi(final int numMessages, int step, final int numActors) throws InterruptedException {
long tim = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(1);
Adder adder = Actors.AsActor(Adder.class,70000);
Hoarde<PiActor> hoarde = new Hoarde<>(numActors, PiActor.class);
for ( int i = 0; i < numMessages; i+=numActors) {
int finalI = i;
hoarde.each( (pia,index) -> pia.$calculatePiFor(finalI + index, step, adder) );
}
// trigger latch once all actors have finished
Actors.yield( hoarde.map( (pia,i) -> pia.$sync() ) ).then( (r,e) -> latch.countDown() );
latch.await();
long duration = System.currentTimeMillis() - tim;
adder.$printPi();
// clean up
hoarde.each( (pia) -> pia.$stop() );
adder.$stop();
System.out.println("TIM ("+numActors+")"+duration);
return duration;
}
}
@RuedigerMoeller
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment