package edu.rice.hj.example.comp322; import edu.rice.hj.api.HjRunnable; import edu.rice.hj.api.HjSuspendable; import edu.rice.hj.api.SuspendableException; import static edu.rice.hj.Module1.asyncNb; import static edu.rice.hj.Module1.launchHabaneroApp; /** *

Lecture2 class.

* * @author Shams Imam (shams@rice.edu) */ public class Lecture2 { /** *

returnInAsync.

* * @param condition a boolean. */ public static void returnInAsync(final boolean condition) { if (!condition) { // this return is not inside the async return; // returns from returnInAsync() } asyncNb(new HjRunnable() { @Override public void run() { System.out.println("Inside async"); if (condition) { // this return only returns from the async, // it doesn't return from the returnInAsync() method return; } // do something else } }); System.out.println("I will be printed if the async is created!"); } /** *

breakAndContinue.

* * @param condition a boolean. */ public static void breakAndContinue(final boolean condition) { WHILE_1: // label to identify the while loop while (condition) { asyncNb(new HjRunnable() { @Override public void run() { while (condition) { break; // Okay } // break; // ERROR --- does not relate to the WHILE-1 loop } }); } } public static class StaticFieldCommunication { static int sum1 = 0, sum2 = 0; public static void main(final String[] argv) { // caller // effectively final variable final int[] X = new int[20]; // Initialize X // Async’s have same access rules as lambdas // effectively final variable are accessible inside lambdas // static fields are accessible inside lambdas launchHabaneroApp(new HjSuspendable() { @Override public void run() throws SuspendableException { asyncNb(new HjRunnable() { @Override public void run() { for (int i = X.length / 2; i < X.length; i++) { sum2 += X[i]; } } }); asyncNb(new HjRunnable() { @Override public void run() { for (int i = 0; i < X.length / 2; i++) { sum1 += X[i]; } } }); } }); final int sum = sum1 + sum2; } } public static class ObjectBasedCommunication { public static void main(final String[] argv) { // caller // effectively final variable final int[] X = new int[20]; // Initialize X // effectively final variable final TwoIntegers r = new TwoIntegers(); // Async’s have same access rules as lambdas // effectively final variable are accessible inside lambdas launchHabaneroApp(new HjSuspendable() { @Override public void run() throws SuspendableException { asyncNb(new HjRunnable() { @Override public void run() { for (int i = X.length / 2; i < X.length; i++) { // accessing field 'sum2' of an effectively final variable and modifying it r.sum2 += X[i]; } } }); asyncNb(new HjRunnable() { @Override public void run() { for (int i = 0; i < X.length / 2; i++) { // accessing field 'sum1' of an effectively final variable and modifying it r.sum1 += X[i]; } } }); } }); final int sum = r.sum1 + r.sum2; } public static class TwoIntegers { int sum1; int sum2; } } }