Starting in JDK 9 build 54, compiler support for private interface methods have been resurrected. This was one feature that was planned for Java 8 and did not make the final cut. It is now part of JEP 213. The primary motivation for this proposal is to enable code sharing between non abstract methods in an interface.

Interface evolution was always a tricky problem to solve in earlier versions of Java. You either need to maintain multiple versions of APIs which creates a technical debt over time or brute force your clients to accommodate new methods which breaks binary compatibility. The need to enhance an interface needed support in interface themselves instead of resorting to other options. This was fulfilled by default methods in interfaces in Java 8. Taking this further, private methods come in handy when we have a reusable block of code that default methods could benefit from. Latest Intellij 14.1 builds started to support JDK 9, so lets code an interface!.

An interface now can contain these:

– constants
– method signatures
– nested types
– default methods (since 1.8)
– static methods (since 1.8)
– private methods (since 1.9)
– private static methods (since 1.9)

Some of the restrictions of private methods include:
– private methods must contain method body
– combination of modifiers not allowed : abstract and private
– private methods in an interface does not disqualify it from being a @FunctionalInterface
– annotations types cannot declare private methods
– name clash not permitted

– cannot reduce visibility of private methods

Possibly Related Posts:


Java 8 will go GA in March 2014. java8_logo The first proposed final draft of Java 8 JSR 337 was released early this week. One of the main components of this JSR is Lambda Expressions for the language (JSR 337). This brings the functional constructs to the language, which will undeniably make Java a top contender among other functional peers (Scala, Groovy, Clojure) on the JVM for Java developers. Conciseness is only part of the story, check out how Java 8 programs start to look with Lambda expressions. While being concise for a casual reader, it clearly makes a case why thinking functional may benefit to Java developers in terms of the powerful constructs it offers. The conciseness does not take away readability of the Java program, instead it makes Java developers feel home and enables functional programming with ease, taking away the heavy lifting usually required for moving away from OO paradigm.

I stole the name “Java.next” from Neal Ford‘s excellent series of articles about functional languages on the JVM. The latest installment of the series was “Java.next: Functional coding styles”. While, the article takes on legacy Java, adding Java 8 to the mix would not hurt. So, let us take his example where you are given a list of names, some of which consist of a single character. You are asked to return the names in a comma-delimited string that contains no single-letter names, with each name capitalized. Here are the various flavors of the implementation taken from the article, while Scala, Groovy and Clojure has its functional version, Java’s implementation is imperative and old school.

Java version:

Scala version:

Groovy version:

Clojure version:

Happy Holidays from the islands

Java 8 version of functional processing

With Java 8, functional interfaces makes this possible with Lambda expressions and Streams make you even more fun when working with Collections in Java 8. Here is the functional version in Java 8.

Switch it to parallelStream() for parallel processing, as simple as that to kick the tires of your cores.

My original intent was to compare with the Java.next languages as perceived by Neal Ford in his article. It is unfair to leave behind some of the cool languages on the JVM. Thanks Luke for bringing this up. I strongly believe top-notch IDE support (Eclipse or Intellij) is a win-win situation for users and language implementors. With that context, I updated my list to include Fantom, Gosu, Xtend, Kotlin, Ceylon in order of their age (oldest first).

Fantom version:

Gosu version

Xtend version:

Kotlin version:

Ceylon version:

Personally, I feel Java 8 and Groovy has better success rate in making developers stay in their comfort zone and still enjoy functional prowess. While, I agree Clojure and Scala versions make their case to different set of developers, I believe maintaining a larger code base will be a challenge, when time to develop and market is ever shrinking, and bringing someone up-to-speed with these language tricks will not be easy. If it looks good, eat it, does not play well when it comes to programming in general. While coming to the newer JVM languages, parallelism is one factor that makes Java 8 easy peasy to deal with. These new breed of languages bring ton of cool features (topic for another blog post!) and attracts developers to the JVM, not just Java developers, which is good for the platform. It remains to be seen in the coming years how well these languages get adopted in mainstream development.

Merry Christmas and Happy New Year everyone!

Update (12/29/2013) : Updated the Java.next languages comparison to include newer JVM languages: Fantom, Gosu, Xtend, Kotlin, Ceylon.

Possibly Related Posts:


The default chunk size in Apache HttpClient 4.3 is set to 2048 bytes. There is no easy way to customize the chunk size in the latest Apache HttpClient release. It looks like the only approach is to implement a custom ClientConnectionFactory that allows to override the default chunk size. Here is an example.

Possibly Related Posts:


Two years ago, I blogged about parallel for each construct using a very early version of lambda prototype compiler. At that time, Data Parallelism was already available in C# TPL, but Java designers were hard at work in bringing this idiom to Java.

Lambda expressions support in Java 8 is here for everyone to give it a spin. Functional touch to Collections library makes it a breeze to program in Java. you get this one-liner using Java 8 Stream API.

There are more such one-liners you can think of using parallel constructs in Java 8. Here is another teaser, send an email blast to all customers.

Streams API brings several of the LINQ as well as PLINQ awesomeness to Java Collections library. Here is an adhoc query over a collection using the new Streams API.

Check it out here for more one-liners. You may want to checkout this article that compares LINQ with Java Streams API. While, there are constraints with the Java Streams proposal, it hits the right balance and there is a pedagogical value to it as well, keeping majority Java developers happy.

Enjoy!

Possibly Related Posts:


Java 8 adds support for bulk data operations (JEP 107) in the Collections library. It is unlikely every forms of bulk data operations will be added to the retrofitted Collections framework, but the language designers are making every possible effort in accommodating general use cases of “filter/map/reduce for Java”. Libraries should make use of parallelization on multi-core platforms in order to perform massive parallelizable operations and this means literally kicking-in your cores to its fullest potential. This area of OpenJDK is undergoing heavy changes, it is possible these APIs are changed or improved before milestone 6 when JDK 8 is officially feature complete. But, they are stable enough to give it a spin today. You can grab the lambda build from here. I have been using the latest Intellij 12 preview for my hands on with the new features in Java 8. It actually supports most of the new Java 8 languauge features and intellisense rocks.

The Streams proposal is well thought of and brings the much sought after functional power to Java and you won’t regret upgrading from Java 6 -> Java 8, if you are still hanging around with Java 6 in that time frame. This one is just a preview of what is coming in Java 8.

Let us implement a method to check if a keyword list exists in a tweet. Here is one way to implement it in plain old Java.

Now, that I am taking the Functional programming course, I would like to compare it with Scala, the mature functional language on the JVM. In Scala, this can be implemented as one liners and there are couple different ways to do this, one using exists and other using the foldLeft function, although exists is my favorite as it is clean and less cryptic.

I can understand why functional programmers are more obsessed with “small is beautiful” theme and hate outright verbosity. Now that all dust has settled with Java’s once uncertain future and stalled innovation, its new steward Oracle is betting on to bring back its lost glory in round 2 and you see that happening with Java 8. Finally, the language brings freshness to Java camp in offering functional constructs to Java and make functional programming in Java a breeze. Here is a teaser:

Isn’t nice to have a one liners in Java too? Java is close, but could reduce some noise as you have to call stream() on the Collection which might seem unnecessary. Stream interface supports a fold operation very similar to Scala’s foldLeft function and implements using a similar approach as of Scala.

Now, let us take this example further, filter tweets matching keywords. This was inspired by Week 3 assignment from the “Functional Programming Principles in Scala” course which btw I am enjoying it so far. Again, you can see Java makes it a cut. I am trying to keep it not being a spoiler.


In this example, you notice that you have to use stream() as well as into() operations to get the result of stream processing. I believe this is a limitation with the iteration 2 Streams implementation which was referred as “the bun problem” that we have to live with.

Streams in Java 8 is making implementing bulk operations a no brainer. While it involves some effort in learning the new concepts, it opens up a new dimension to library developers. Thanks to JSR 335 which brings Java up to speed with other cool languages out there in the planet.

For fun, I want to toss in a new exists() API to the Stream interface so I could use it to filter on my keywords list. This can be done with the help of extension methods, another new concept in Java 8.


Basically, I am delegating the implementation to anyMatch() for simplicity as both reveal the same purpose. Here is a custom List implementation that exposes this API on the collection. This is a primitive implementation, which btw I am trying to keep this updated with the recent library changes. I hope there is a better way to do this, but the point is, it enables developers to extend the Streams framework and fill in special cases.

exists() variant of the code is shown below.


There are several new concepts in the library that requires functional mindset to fully benefit from it. You can switch these Streams to use a parallel version, by using parallel() instead of stream() on the Collection. Stream operations are classified as lazy and eager based on their implementation.
I hope to uncover some of these new concepts in the coming months. I wish function types made into Java 8, but that is different story for another day. Enjoy functional programming in Java!

I have covered Lambdas in the past and this excellent JavaZone talk by Angelika Langer should bring you up to speed with the current state of affairs with Lambdas in Java 8. You can also find Maurice Naftalin’s LambdaFAQ useful.

Lambdas in Java 8 from JavaZone on Vimeo.

Update (10/20/2012) : Updated samples to use method reference and built with the latest Lambda build 61. Clarified the bun-problem with streams proposal.
Update (11/20/2012) : Updated MyList implementation to compile with the latest API changes and much cleaner implementation.
Update (2/3/2013) : Updated code to compile with the latest lambda build 75.
Update (6/15/2013) : Updated code to compile with the latest lambda build 94.

Possibly Related Posts:


It is nice to download the course materials from coursera.org and view them offline especially the mp4 video lectures. Here is a nice utility which exactly does that. I used this script to download video lectures for Functional Programming Principles in Scala course. It comes handy to listen from smartphone!

git clone https://github.com/jplehmann/coursera
cd coursera
./coursera-dl progfun-2012-001 -u **** -p *****

Possibly Related Posts:


Aloha from Hawaii! Shame on me to not blog for months. Well, honestly I have been quite busy during the past few months. With the big move to Hawaii in December and the recent launch of Floify kept me occupied. Although moving to a new place is fun, getting settled on an island can sometimes be more stressful. Now all that is taken care, there is no good reason to not blog from rainbow nation 🙂

Recently, I was working with an evaluator implementing a proof of concept where they had a requirement for scheduling workflows from a web service request. In Flux, this can be easily implemented as a trigger which typically waits for an event to occur. Flux supports popular triggers out of the box, which are either based on timer or database condition or file or audit trail or mail. While ago, I implemented a custom web service trigger which supports both SOAP and HTTP requests and expedites the workflow to the subsequent step. The sample testcase below shows how web service trigger can be implemented in your Flux workflows.

The sample client code that expedites the trigger is shown below.

With this plugin, your workflows can be designed to trigger based on web service requests and it also allows users to configure an embedded web server that runs part of the workflow. If this were one shot workflows, this nicely fits the bill. If the requirement were to support a recurring workflow, I would classify this approach as heavy weight mainly because it spins a web server for each run of your workflow which may not be ideal for high performance workflows. It makes more sense to reuse a single web server instance that accepts requests and triggers a workflow template from the repository. I do not believe this can be easily supported without making some core changes in Flux. But, it is not the end of the world, there is a more efficient way to implement this in Flux today by using Flux Cluster APIs.

Flux 7.11 Operations Console exposes set of APIs that allows clients to talk to Flux engine cluster via simple HTTP interface. In essence, Flux Opsconsole acts as a web service trigger for the cluster. You can find the documentation of these APIs here. The API that schedules a workflow template from repository will be available in 7.11.4. If you would like to try out this, you can request a 7.11.4 build from Flux support, we would be happy to send one on your way. The Operations Console deploys HTTP resources that can be accessed in a number of ways. If you were a Java shop, you would consider something similar shown in the Gist below. This sample uses Jersey APIs to POST a multipart request to the endpoint. You just need to toss in restaction.jar which is part of the Flux distribution.

In this example, we add three properties to a multipart request. The first one “template” is required and specifies the name of the template in the repository. The “category” and “rate” are optional variables that will be made available in your workflow instance. You can add as many data points that you would like to pass on to your workflow instance. You can also optionally customize the name of the workflow instance that you would like to spin off from the repository by setting the “namespace” property in the request.

There is another API that might interest you as well. This API schedules a given flow chart to the engine. The major difference here is your are exporting a workflow file to the engine instead of spinning an instance from existing repository template.

Enjoy developing in Flux and Mahalo for stopping by!

Possibly Related Posts:


Flux’s RestAction is the go-to construct for users orchestrating Flux workflows that involve web service integration. Be it HTTP-based services or SOAP-based services that implement HTTP binding, RestAction comes very handy for developers. Flux has a WebServiceAction which talks SOAP exclusively for services that implement WS-* such as Addressing, Security etc. RestAction has neat XPath integration, which allows users to navigate the response using XPath query and bind the result to domain model that can be seamlessly used in your workflow context.

In this post, let us look at a simple Weather Web Service which supports both SOAP and HTTP binding. I will be using Eric’s simple test framework to demonstrate the use of RestAction and WebServiceAction in your Flux workflow.

Let us see how to invoke the Weather web service using the traditional WebServiceAction that uses the WSDL. We pass the zip code as a parameter to GetCityForecastByZIP operation and the response is handled using a JavaAction. In this case the response is bound to ForecastReturn complex type.

package flux.test;

import com.cdyne.ws.weatherws.Forecast;
import com.cdyne.ws.weatherws.ForecastReturn;
import flux.*;
import org.junit.Test;

import java.net.URL;
import java.util.Properties;

public class WeatherWebServicesTest extends AbstractFluxTest {

 @Test
 public void testWebServiceAction() throws Exception {
   log.info("[START] FluxTest.testWebServiceAction");
   String namespace = "/FluxFlowChart";

   FlowChart flowChart = engineHelper.makeFlowChart(namespace);

   WebServiceAction webServiceAction = flowChart.makeWebService("GET Weather Info");

   // Specify the WSDL the web service action is to use.
   webServiceAction.setWsdl(new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"));

   // Specify the signature of the method to call.
   webServiceAction.setListenerSignature("GetCityForecastByZIP(String)");

   // Specify the arguments to pass to the method.
   webServiceAction.setArgument(0, "59102");

   JavaAction javaAction = flowChart.makeJavaAction("Java Action");
   javaAction.setListener(WebServiceActionListener.class);

   webServiceAction.addFlow(javaAction);

   engine.put(flowChart);

   waitForRuns(namespace, 1, 5, 30);

   log.info("[END] FluxTest.testWebServiceAction");
 }
}

The ActionListener implementation that processes the ForecastReturn from WebServiceAction.

Let us invoke the same operation using RestAction, which uses the HTTP binding. Here we set the query parameter “ZIP” and bind the response to ForecastReturn POJO (generated using: xjc -wsdl http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl).

  @Test
  public void testRestActionGET() throws Exception {
    log.info("[START] FluxTest.testRestActionGET");
    String namespace = "/FluxFlowChart";

    FlowChart flowChart = engineHelper.makeFlowChart(namespace);

    RestAction restAction = flowChart.makeRestAction("GET Weather Info");

    // Specify the URL the rest action is to use.
    restAction.setBaseUrl(new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP"));

    // Specify the Action type.
    restAction.setActionType(RestActionType.GET);

    // Specify the Response type.
    restAction.setResponseType(ForecastReturn.class);

    // Specify the query parameters to be sent as part of the request.
    Properties queryParams = new Properties();
    queryParams.put("ZIP", "59102");

    restAction.setQueryParameters(queryParams);

    JavaAction javaAction = flowChart.makeJavaAction("Java Action");
    javaAction.setListener(RestActionListener.class);

    restAction.addFlow(javaAction);

    engine.put(flowChart);

    waitForRuns(namespace, 1, 5, 30);

    log.info("[END] FluxTest.testRestActionGET");
  }

In this example, we are performing an XPath query that returns an array of Forecast elements.

  @Test
  public void testRestActionXPathArray() throws Exception {
    log.info("[START] FluxTest.testRestActionXPathArray");
    String namespace = "/FluxFlowChart";

    FlowChart flowChart = engineHelper.makeFlowChart(namespace);

    RestAction restAction = flowChart.makeRestAction("GET Weather Info");

    // Specify the URL the rest action is to use.
    restAction.setBaseUrl(new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP"));

    // Specify the Action type.
    restAction.setActionType(RestActionType.GET);

    // Specify the query parameters to be sent as part of the request.
    Properties queryParams = new Properties();
    queryParams.put("ZIP", "59102");

    restAction.setQueryParameters(queryParams);

    // Specify the XML namespace, if one defined
    Properties namespaces = new Properties();
    namespaces.put("ws", "http://ws.cdyne.com/WeatherWS/");
    restAction.setNamespaces(namespaces);

    // Specify the XPath expression using the defined namespace
    restAction.setXpathExpression("/ws:ForecastReturn/ws:ForecastResult/ws:Forecast");// this xpath returns an array of Forecast elements

    // Specify the XPath response type.
    restAction.setXpathResponseType(Forecast[].class);

    JavaAction javaAction = flowChart.makeJavaAction("Java Action");
    javaAction.setListener(RestActionListener.class);

    restAction.addFlow(javaAction);

    engine.put(flowChart);

    waitForRuns(namespace, 1, 5, 30);

    log.info("[END] FluxTest.testRestActionXPathArray");
  }

In this example, we are performing an XPath query that returns the first Forecast element from the array.

  @Test
  public void testRestActionXPathPOJO() throws Exception {
    log.info("[START] FluxTest.testRestActionXPathPOJO");
    String namespace = "/FluxFlowChart";

    FlowChart flowChart = engineHelper.makeFlowChart(namespace);

    RestAction restAction = flowChart.makeRestAction("GET Weather Info");

    // Specify the URL the rest action is to use.
    restAction.setBaseUrl(new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP"));

    // Specify the Action type.
    restAction.setActionType(RestActionType.GET);

    // Specify the query parameters to be sent as part of the request.
    Properties queryParams = new Properties();
    queryParams.put("ZIP", "59102");

    restAction.setQueryParameters(queryParams);

    // Specify the XML namespace, if one defined
    Properties namespaces = new Properties();
    namespaces.put("ws", "http://ws.cdyne.com/WeatherWS/");
    restAction.setNamespaces(namespaces);

    // Specify the XPath expression using the defined namespace
    restAction.setXpathExpression("/ws:ForecastReturn/ws:ForecastResult/ws:Forecast[1]");// this xpath returns the first element from the list

    // Specify the XPath response type.
    restAction.setXpathResponseType(Forecast.class);

    JavaAction javaAction = flowChart.makeJavaAction("Java Action");
    javaAction.setListener(RestActionListener.class);

    restAction.addFlow(javaAction);

    engine.put(flowChart);

    waitForRuns(namespace, 1, 5, 30);

    log.info("[END] FluxTest.testRestActionXPathPOJO");
  }

In this example, we are performing an XPath query that returns an attribute of ForecastReturn element.

  @Test
  public void testRestActionXPathAttribute() throws Exception {
    log.info("[START] FluxTest.testRestActionXPathAttribute");
    String namespace = "/FluxFlowChart";

    FlowChart flowChart = engineHelper.makeFlowChart(namespace);

    RestAction restAction = flowChart.makeRestAction("GET Weather Info");

    // Specify the URL the rest action is to use.
    restAction.setBaseUrl(new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP"));

    // Specify the Action type.
    restAction.setActionType(RestActionType.GET);

    // Specify the query parameters to be sent as part of the request.
    Properties queryParams = new Properties();
    queryParams.put("ZIP", "59102");

    restAction.setQueryParameters(queryParams);

    // Specify the XML namespace, if one defined
    Properties namespaces = new Properties();
    namespaces.put("ws", "http://ws.cdyne.com/WeatherWS/");
    restAction.setNamespaces(namespaces);

    // Specify the XPath expression using the defined namespace
    restAction.setXpathExpression("/ws:ForecastReturn/ws:City/text()");// this xpath returns the name of the city

    // Specify the XPath response type.
    restAction.setXpathResponseType(String.class);

    JavaAction javaAction = flowChart.makeJavaAction("Java Action");
    javaAction.setListener(RestActionListener.class);

    restAction.addFlow(javaAction);

    engine.put(flowChart);

    waitForRuns(namespace, 1, 5, 30);

    log.info("[END] FluxTest.testRestActionXPathAttribute");
  }

The ActionListener implementation that processes various results from the RestAction is shown below.

Here is a screenshot of the test output from Intellij.

You need to toss in the following jars from Flux distribution:

flux.jar
lib/restaction.jar
lib/webserviceaction.jar
lib/commons-logging-1.1.1.jar
examples/software_developers/web_services/lib/weatherws-generated.jar

Test dependencies include:

log4j-1.2.15.jar
junit-4.9.jar


Download the latest Flux 7.11 version here and check it out. The samples are available in flux-goodies bitbucket repository. You can also find more samples ($FLUX_HOME/examples/software_developers/web_services and $FLUX_HOME/examples/software_developers/rest_services) in the latest Flux 7.11.2 distribution. Enjoy!

Possibly Related Posts:


Almost a year later since publishing the original Lambda proposal, JSR 335 EG has finally decided to adopt C# style syntax for Java 8 Lambda expressions. Brian has outlined the formal model for the new C# style syntax in his mail to lambda-dev:

lambda = ArgList Arrow Body
ArgList = Identifier
| “(” Identifier [ “,” Identifier ]* “)”
| “(” Type Identifier [ “,” Type Identifier ]* “)”
Body = Expression
| “{” [ Statement “;” ]+ “}”

Last week, Maurizio has pushed an updated compiler implementation that aligns with this new C# style syntax. I basically converted the Lambda examples used in my original post which I wrote an year ago when the initial straw-man syntax was prototyped. This post is essentially a take2, that illustrates Lambda expressions with the new C# style syntax and covers the latest developments in Lambda community. Honestly speaking, I enjoyed using the new syntax as part of this exercise. Enjoy!

Lambdas are available in the form of anonymous inner classes in Java. Anonymous inner classes are a form of nested classes that has no name and exhibits the following behavior as detailed in JLS 15.9.5.

  • An anonymous class is never abstract
  • An anonymous class is always an inner class; it is never static
  • An anonymous class is always implicitly final

One common use of anonymous inner classes is to create function objects in Java on the fly. [Refer Item 21 in Effective Java 2nd Edition pg 103]

Let us look at sorting an array of strings based on its length using an anonymous Comparator instance.

        String[] teams = {"Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"};
        Arrays.sort(teams, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });

To create process objects, such as Runnable, Thread, or TimerTask instances.

        final ExecutorService executor = Executors.newCachedThreadPool();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("I am Runnable");
            }
        });

Anonymous classes have many limitations as outlined in Item 22 in Effective Java 2nd Edition [pg 108]. With Lambda expressions, you should be able to rewrite these samples more concisely eliminating the bulky syntax that comes with anonymous inner classes :

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Sample1 {

  public static void main(String... args) {
    final ExecutorService executor = Executors.newCachedThreadPool();
    // assignment context
    Runnable task = () -> System.out.println("I am Runnable"); //take 1
    executor.submit(task);

    // method invocation context
    executor.submit(() -> {System.out.println("I am Runnable");}); //take 2
    executor.shutdown();
  }
}

Array sorting using a comparator with Lambda expressions is a one liner:

import java.util.Arrays;
import java.util.Comparator;

public class Sample2 {
	public static void main(String... args) {
		String[] teams = {"Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"};
		final Comparator<String> c = (s1, s2) -> s1.length() - s2.length();
		Arrays.sort(teams, c); //take 1
		Arrays.sort(teams, (s1, s2) -> s1.length() - s2.length()); //take 2
	}
}

So, what next? Let us do some hands-on with these Lambdas and explore what Lambdas has to offer for Java developers. I setup the new prototype on my Windows environment following Remi’s instructions. It was fairly straight forward (all you need is Mercurial Client, Apache Ant, and JDK 7).

Here is a simple build script (build.bat) I used in Windows, that you can place in the “make” sub-directory under “langtools” :

ant -Dboot.java.home=C:\jdk1.7.0 clean build

This would create classes.jar under “dist\lib” sub-directory. You need to place this jar in your classpath when using the prototype.

You can use the following batch scripts for compiling and running your Lambda examples (tested with the JDK 7 GA release).

javac.bat

@echo off
C:\jdk1.7.0\bin\java.exe -cp classes.jar com.sun.tools.javac.Main %1

java.bat

@echo off
C:\jdk1.7.0\bin\java.exe -cp classes.jar;. %1

It is required to include classes.jar in the classpath due to runtime dependencies that are not available in the binary build. To make sure if you are running the prototype compiler, the output should show “internal” tag:

C:\jdk8-lambdas\samples>javac.bat -version
javac 1.7.0-internal

Let us look at a simple example:

public class SimpleLambda {
  interface HelloWorld {
    void greet();
  }

  {
    HelloWorld greeting = () -> System.out.println("Hello World!");//nilary Lambda expression
    greeting.greet();
  }

  public static void main(String... args) {
    new SimpleLambda();
  }
}

To compile this example:

javac.bat SimpleLambda.java

To run this example:

java.bat SimpleLambda

Voila, you ran your first lambda example successfully if you see “Hello World!” output.

Let us look at another example which uses parameterized types in this case.

public class Sample3 {
  interface Squarer<X, Y> {
    Y square(X x);
  }

  public static void main(String... args) {
    Squarer<Integer, Integer> s = (x) -> x * x;// 1-ary Lambda expression
    System.out.println(s.square(5));
  }
}

In both these examples, you notice a pattern commonly referred to as single abstract method (SAM), defined using an interface with exactly one abstract method. This is a structural property identified by the compiler and it does not take into account methods inherited from java.lang.Object (as in java.util.Comparator).

For example, Runnable, Callable, etc belongs to this category of SAM types that can be converted in the context of assignment as shown below.

final Runnable task = () -> System.out.println(“I am Runnable”);

In this code, “task” is an Runnable instance, while the lambda expression () -> … is not. Only after conversion, the target type becomes an instance of that SAM type.

Syntax – The Holy Grail of Lambda

A lambda expression is written as a parameter list, followed by the -> token, followed by an expression or a statement block. In case of single line Lambda expression, return keyword can be omitted. Block of statements are surrounded with {} and if you need to return a result, you need to specify the return keyword.

Note ‘thin’ arrow is still used (instead of ‘fat’ (=>) arrow as used in C#). This is still under discussion. I personally like ‘thin’ arrow and ‘fat’ arrow does not really help visually.

Lambdas in Java exhibit the following behavior :

  • An interface with exactly one abstract method is referred to as an functional interface (fka SAM types).
  • Lambdas are not instances of classes.
  • Lambdas can only be converted to SAM interfaces.
  • SAM types are instances of classes.
  • Lambdas are lexically scoped.

Lambda definition (excerpt from draft)

A lambda expression e is convertible-to a SAM type S if an anonymous inner class that is a subtype of S and that declares a method with the same name as S’s abstract method and a signature and return type corresponding to the lambda expressions signature and return type would be considered assignment-compatible with S.

The return type and exception types of a lambda expression are inferred by the compiler; the parameter types may be explicitly specified or they may be inferred from the assignment context.

The type of a formal parameter can be omitted, in which case the compiler will infer a type from the target type of the lambda conversion. Let us see couple examples where the types are inferred by the compiler.

public class Sample4 {

  enum Decision {
    APPROVE, DECLINE, APPROVE_REFER
  }

  interface DecisionService {
    Decision getRiskDecision(Applicant applicant);
  }

  class Applicant {
    private int score;

    public Applicant(int score) {
      this.score = score;
    }

    public int getScore() {
      return score;
    }
  }

  public void test() {
    DecisionService cs = (a) -> {
    if (a.getScore() > 700) {
      return Decision.APPROVE;
    } else if (a.getScore() > 600 && a.getScore() < 650) {
      return Decision.APPROVE_REFER;
    } else {
      return Decision.DECLINE;
    }};
    Decision decision = cs.getRiskDecision(new Applicant(800));
    System.out.println(decision.toString());
  }

  public static void main(String... args) {
    new Sample4().test();
  }
}

In line #24 above, the type of the formal parameter Applicant is inferred by the compiler.

public class Sample5 {

  class Payment {
    private int amount;

    Payment(int amount) {
      this.amount = amount;
    }

    public int getAmount() {
      return amount;
    }
  }

  interface PaymentProcessor {
    void process(Payment pmt);
  }

  public void test() {
    invokeProcessor((pmt) -> log("Processed # " + pmt.getAmount() + " at " + new Date()));
  }

  void invokeProcessor(PaymentProcessor processor) {
    processor.process(new Payment(42));
  }

  void log(String message) {
    System.out.println(message);
  }

  public static void main(String... args) {
    new Sample5().test();
  }
}

In line #20, the type of the formal parameter Payment is inferred by the compiler.

Here is the definition of SAM and non-SAM types as explained in one of the Lambda test case.

SAM types:
1. An interface that has a single abstract method
2. Having more than one distinct methods, but only one is “real”, the others are overriden public methods in Object – example:

Comparator<T>

3. Having more than one methods due to inheritance, but they have the same signature
4. Having more than one methods due to inheritance, but one of them has a subsignature of all other methods

    a) parameter types compatible
    b) return type substitutable
    c) thrown type not conflicting with the thrown clause of any other method
    d) mixed up

5. Type-dependent SAM types

non-SAM types:
6. An interface that has a single abstract method, which is also public method in Object
7. Having more than one methods due to inheritance, and none of them has a subsignature of all other methods

What has changed since then in the Lambda community?

Well, the first thing that happened in the past year was the formation of expert groups; JSR 335 for Lambda support in Java 8 and JSR 337 umbrella JSR for Java 8. Two polls were conducted in June on lambda-dev mailing list and the results mostly favored BGGA style syntax. Choosing the syntax that C# and Scala broadly share is a wise move by the JSR 335 EG. Did any one catch up with the replacement term for SAM? It is called “functional interface”, although SAM is widely popular among lambdaphiles.

Virtual extension methods approach was revised since the original strawman proposal. Brian explains this beautifully from conception to implementation in this paper Interface evolution via virtual extension methods. Virtual extension methods will be implemented as a VM feature, which makes it transparent like any other method invocation for non-Java languages. The following JVMLS talks explain the latest developments in virtual extension methods and lambda implementation strategies. I strongly encourage to watch them as it is the only source of information for people outside the JSR 335 Expert Group.


[Photo credit: http://www.lumaxart.com/]

Possibly Related Posts:


Automated SCP file transfers can be orchestrated in your Flux workflow using SCPAction. This action supports file uploads or downloads using SCP. SCP is basically a remote copy (rcp) through a SSH tunnel. It is easy to setup key-based SSH login for your systems, here is one article describing the steps for Mac. You could also run arbitrary system commands or scripts using this action.

Here is a screen shot showing SCPAction configuration that downloads logs from a linux host.

Here is a screen shot showing SCPAction configuration that executes a remote disk check command for a linux host.

A sample test case that shows how this action could be integrated within a Flux workflow using Java API.

Maven users could just drop this dependency in your POM to use this plugin in your project.

<dependency>
  <groupId>com.fluxcorp.plugins</groupId>
  <artifactId>scp-action</artifactId>
  <version>1.0.3.SNAPSHOT</version>
</dependency>

Make sure you include this maven repository where the plugin snapshots are deployed.

<repository>
  <id>sonatype-nexus-snapshots</id>
  <name>sonatype-nexus-snapshots</name>
  <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

There are few more interesting plugins available, you can check the project wiki for more details. Download the latest Flux 7.11 version and check out these cool plugins. Enjoy!

Possibly Related Posts: