Lambdas

From CSE231 Wiki
Revision as of 06:02, 31 January 2017 by Finn (talk | contribs) (Created page with "Lambdas are one of the most recently-added features in Java, essentially allowing one to pass a function as an parameter to a method. The functionality provided by lambdas has...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Lambdas are one of the most recently-added features in Java, essentially allowing one to pass a function as an parameter to a method. The functionality provided by lambdas has always been available, but lambdas allow the syntax to be significantly more succinct. This page will discuss alternatives to lambdas in order to better explain what lambdas are doing behind the scenes. It is based on the Java Tutorials, but has been adapted for the code used more frequently in CSE 231.

The Problem

In Habanero-Java, the async() method is used to spawn a task that will run asynchronously to the rest of your program. Ideally, the async() method would take a function as a parameter. The async() method could then call this function in parallel with the rest of your code. In Java, however, functions cannot be passed as parameters to methods. Only objects (and primitive types) can be passed in.

To solve this problem, the async() method takes an HjSuspendable as a parameter. HjSuspendable is an interface which contains a single method: run(). You have to pass in an instance of a class that implements HjSuspendable--thus guaranteeing that it has a run() method--and the async() method will call the run() method of your object asynchronously.

Separate Classes

A straightforward solution is to write your own class that implements HjSuspendable. Let's say, for example, that you want to print "Hello, World!" asynchronously. The pseudocode for this would be something like this:

async {
  print "Hello, World!"
}

We could create a class called PrintHelloWorld that implements HjSuspendable. It would look something like this:

public class PrintHelloWorld implements HjSuspendable {

    @Override
    public void run() throws SuspendableException {
        System.out.println("Hello, World!");
    }

}

An instance of this class could then be passed into the async() method. For example:

HabaneroClassic.async(new PrintHelloWorld());

This code would perform the way we would expect from the pseudocode.