package edu.rice.comp322; import edu.rice.hj.runtime.actors.Actor; import edu.rice.hj.runtime.actors.Message; import static edu.rice.hj.Module0.launchHabaneroApp; /** * Solution to Worksheet 5. * * @author Shams Imam */ public final class Lec29Slide4EchoActor { /** * Disallow instance creation of utility class. */ private Lec29Slide4EchoActor() { super(); } /** *

main.

* * @param args an array of {@link String} objects. */ public static void main(final String[] args) { final String[] messages = new String[]{"Hello", "World", "with", "actors.", StringMessage.END}; // Actor instances may be safely created outside a global finish final EchoActor echoActor = new EchoActor(); // messages may be sent to the actor, but they won't be processed until // the actor is started inside some finish scope for (int i = 0; i < 2; i++) { final String loopMessage = messages[i]; System.out.println("Sending: " + loopMessage); echoActor.send(new StringMessage(loopMessage)); busyWait(); } launchHabaneroApp(() -> { System.out.println("Starting actor..."); // Actors can only be started inside a finish scope // Actor starts processing messages only after it has been started echoActor.start(); // send more messages to the actor for (int i = 2; i < messages.length; i++) { final String loopMessage = messages[i]; System.out.println("Sending: " + loopMessage); echoActor.send(new StringMessage(loopMessage)); busyWait(); } System.out.println("Waiting for actor to terminate"); }); System.out.println("Outside the global finish"); } private static void busyWait() { // busy wait for (int j = 0; j < 100000; j++) { Math.random(); } } public static final class StringMessage implements Message { public static final String END = "__END__"; /** * The wrapped string message */ public final String message; /** * Constructor. * * @param pMessage The string to wrap. */ public StringMessage(final String pMessage) { this.message = pMessage; } } public static final class EchoActor extends Actor { /** * Constructor. */ public EchoActor() { super(); } @Override protected void process(final StringMessage theMsg) { System.out.println(" Processing: " + theMsg.message); if (StringMessage.END.equals(theMsg.message)) { System.out.println("Terminating actor."); exit(); } } } }