using Nashorn’s jjs for experimenting

In Java 8, Oracle introduced the new Nashorn engine and is encouraging the use of jjs. It’s a RPEL (read print evaluate loop) for JavaScript. Since JavaScript can call Java, this allows experimenting with Java APIs like you do in other languages like Python and Ruby. It works better in those languages though.

Cay Horstmann’s book, Java SE 8 for the Really Impatient, had good exercises for lambdas so I decided to the end of chapter exercises for Nashorn.

Exercise 1 – Play with jjs to experiment with an API you want to explore; did you find it easier than writing test programs in Java?

Nope. The so called advantage of using jjs is that you don’t need to write the plumbing code. But an IDE can generate a class and main method in a couple clicks.

  1. Strike 1 – With jjs, I need to type in the package of name of classes I want to use rather than just letting Eclipse deal with imports for me.
  2. Strike 2 – jjs doesn’t have tab complete (autocomplete) which means I have to type in the full class/method name of the class I am experimenting with. If I was an expert, I wouldn’t be in jjs in the first place.
  3. Strike 3 – jjs doesn’t support the up arrow. Which means when I make typos (see strike 1 and 2), I get to type the whole thing again.

Exercise 2 – Using JJS and the stream library iteratively work out a solution to the problem to print a filtered list of unique long words in sorted order and see how it compares to your usual workflow.

Here was my workflow with jjs:

  1. Create the test file in a text editor
  2. Run ./jjs
  3. Create a path object
    Attempt # Code Error Comments
    1 jjs> var paths = Paths.get(‘path/words.txt’) <shell>:1 ReferenceError: “Paths” is not defined Forgot to type the package name. Don’t know it by heart anyway. Need to look it up in the JavaDoc.
    2 jjs> var paths = java.nio.file.Paths.get(‘path/words.txt’) Success
  4. Read the file
    Attempt # Code Error Comments
    1 jjs> List<String> list = java.nio.files. Files.readAllLines(path) ECMAScript Exception: ReferenceError: <shell>:1:11 Invalid left hand side for assignment It’s JavaScript, not Java so no type declaration. Should just use var.
    2 jjs> var list = java.nio.files. Files.readAllLines(path)  <shell>:1 ReferenceError: “path” is not defined Typo in variable name. I wish I named it path, not paths. But I want to do the exercise in order and not go back.
    3 jjs> var list = java.nio.files. Files.readAllLines(paths) java.lang.RuntimeException: java.lang. ClassNotFoundException: java.nio.files. Files.readAllLines Typo in package name. It should be file and not files
    4 jjs> var list = java.nio.file. Files.readAllLines(paths) java.lang.RuntimeException: java.nio.file. NoSuchFileException: path/words.txt Missing forward slash in path name. On the bright side, I can rename the variable without feeling like I’m messing up the experiment.
    5 jjs> var path = java.nio.file. Paths.get(‘/path/words.txt’) Worked as expected (but at this point, I’m typing into this blog post and copy/pasting into the jjs console
    6 jjs> var list = java.nio.file. Files.readAllLines(paths)  java.lang.RuntimeException: java.nio.file. NoSuchFileException: path/words.txt Sigh. Didn’t use the corrected variable name
    7 var list = java.nio.file. Files.readAllLines(path) Worked as expected
  5. Filter the long words
    Worked.

    Attempt # Code Error Comments
    1 jjs> list.stream().grep({ l -> l.length() > 12}) ECMAScript Exception: SyntaxError: <shell>:1:23 Expected : but found – This is completely wrong. Aside from the stream() call, it is using Groovy syntax. (I code Groovy at a command line so my fingers started there)
    2 jjs> list.stream().filter( l -> l.length() > 12) ECMAScript Exception: SyntaxError: <shell>:1:30 Expected an operand but found Hmm. Puzzled. it looks right this time. I copy/pasted into my IDE and it compiled. I then started searching online and found out that you have to use a function literal. (This was in the book. I forgot about it)
    3 jjs> list.stream().filter(function(e) { return e.length() > 12 }) Prints reference to stream (as does Java.) Now can add the print
    4 jjs> list.stream().filter(function(e) { return e.length() > 12 }).forEach(System.out::println) ECMAScript Exception: SyntaxError: <shell>:1:79 Expected , but found : Not surprised that :: doesn’t work since -> doesn’t. Now for the long way.
    5 jjs> list.stream().filter(function(e) { return e.length() > 12 }).forEach(function(e) { print(e) }) Works as expected
  6. Add sorting, uniqueness and refactor
    Attempt # Code Error Comments
    1 jjs> list.stream().filter(function(e) { return e.length() > 12 }).sorted().forEach(function(e) { print(e) }) Sorting worked
    2 jjs> list.stream().filter(function(e) { return e.length() > 12 }).sorted().distinct().forEach(function(e) { print(e) }) Uniqueness filter worked
    3 jjs> list.stream().filter(function(e) e.length() > 12 ).sorted().distinct().forEach(function(e)  print(e) ) Remove unneeded code

 My thoughts

That was so far away from being easier that it was ridiculous.  I’m comfortable with the NIO and lambda APIs. This shouldn’t have been hard. The Java version is:

import java.io.*;
import java.nio.file.*;
import java.util.*;

public class Exercise2 {
   public static void main(String[] args) throws IOException {
      Path path = Paths.get("/path/words.txt");
      List<String> list = java.nio.file.Files.readAllLines(path);
      list.stream()
                .filter(l -> l.length() > 12)
                .sorted()
                 .distinct()
		.forEach(System.out::println);
     }
}

java 8 lambdas from the nyc java meetup

I really liked the Java 8 Lambda talk from yesterday evening’s meetup so I’m blogging about it.  I like lambdas for the same reasons I like regular expressions – so much power and clarity!   The speaker was Timothy Fagan from Lab 49.  Photos of most of the slides are on the meetup website.  (not sure if you have to be a member of the meetup to view the pictures.)  Ok, here’s what I learned.  There are many blog posts on lambdas better than mine like the “Everything about Java 8” one.  I’m blogging anyway to solidify my understanding.

Where development is up to

  • Feature complete now.
  • General Availability March 2014.
  • Oracle delayed Java 8 date so lambdas would be included

Where we came from

  • Java has always had functors (objects that are classes)
  • Java 1.0 – could create classes to be functors – for example Runnable interface with run method
  • Java 1.1 invented anonymous inner classes  – complexity, performance issues (megamorphic call size or stack?)
Syntax
General case:
  • (paramList) -> expression | { statements}

Special case for single parameter: (Can leave out parens if one param. Need parens if zero params)

  • param -> expr | { stmt }
The return type is expr or return type of stmt.  stmt can return void if no return value
Examples
Uses signatures and return type to match new thread sig. This conforms to Runnable interface – returns void
  • new Thread(() -> System.out.println(“foo”))
Uses type inference to determine types of a and b
  • words.sort ((a,b) -> a.length() – b.length())

Only invokes lambada expression if logger set to right level.  This is a new interface that returns String

  • Logger.finest (()-> f.toString())
Only does expensive call if key not already in map:
  • map.computeIfAbsent(1234444, number-> getObjectFromDB())
Cast tells Java they are strings.  Interesting:  First time in Java you can have an object that will require a cast in order to compile when assigned to object.  May need to cast if ambiguous which constructor it uses

  •  Comparator c = (Comparator<String>) (a,b) -> a.length() – b.length().
General
  • Oracle combed thru java api looking for opportunities to use lambada expressions
  • Currently error messages are confusing. Builds on wildcard confusing messages
  • Can use lambda epressions in code you write if interface with a single method
  • A lambda is like a method that you dont know the name of on the class you are coding
    Foo..lambda$0 – class and method
    foo$$Lambda$1.methodYouCalled – link from your class to lambda – synthetic method – can’t view source
  • @Functional – requires interface has only one interface so can use as lambd
  • Can build own currying. Need to read about it – went over my head
  • Intellij idea community edition already supports lambdas
  • Jdk8.java.net has javadoc
 Scope
  • Lambdas are scoped in “this” scope not an anonymous inner class
  • System.out.println(this) prints current method name. Gives error if try in static method
  • Can refer to local var of param without having to use final keyword unlike anonymous inner classes  Still needs to be effectively final. Cant reassign after lambda expression. Compiler will catch you if you try to assign it.
  • Local vars are “caputred” which requires a new lambda to be created each time. Noncapturing lambda expressions will reuse instances. If not capturing, don’t need to worry about heap/garbage collector.
  • “this” refers to the point of creation of the lambda expression.  Not necessarily the current class (if passed around). Has some characteristics of a closure, but not all characteristics of closures
Limitations
  • Cannot break or continue outside of lamdba expression but can do so within block of statements in lambda
  • Cannot access non effectively final variables
  • Cannot implement abstract classes even single abstract method (SAM) abstract classes. Must use interfaces.
  • Exceptions in a lambda handled as per anonymous inner classes . A pain if functional interface does not throw exception. Would need a try catch to convert it.
Method References
These are all equivalent:
  • names.forEach(s -> sop)
  • names. ForEach(System.out::println) – uses method references – this is println on a specific object (system.out)
  • Static final Consumer PRNT =  System.out::println; names.forEach(PRINT)
Consumer has apply method of type T. So it can infer to pass forEach param to println. Can be more complex. Can have Printstream::println in which case must pass object to call println on as well.
Chaining with Streams
Stream.of(a,b,c).peek(a->sop)anyMatch(a->a.equals(r))
  • Peek doesn’t alter state. Can insert any where in chain to debug what is going on in stream
  • AnyMatch checks if any are true.    (The presenter wasn’t sure off the top of his head if it is a short circuit operator.  I just checked; it is)
  • AnyMatch lambda must create each time called because r is a variable so caputring. Peek lambda only created once. Don’t know if performance hit enough to worry about but suspect not. And even if a problem now just in time compiler will probably optimize it by ship date
Stream is a one time provider of values. May create lazily on demand. Permits for infinite streams – don’t try to count on one of those!  Examples:
  • Arrays.stream()
  • BufferedReader.lines()
  • IntStrem.range(0,100)
  • IntStream.ints().limit(100)
  • Random.ints() – infinite stream
  • ZipFile.stream()
Methods on Stream
Intermediate – defers execution.  Does not execute until need to.  That way can optimize if don’t need all values
  • Map , reduce, flatmap, mapTo
  • Filter, substream, limit, sorted, distinct (substream means skip first x)
  • Peek, parallel
Terminal – must be at end of chain
  • ForEach, count, min, max, sum (only on numeric streams)
  • AllMatch, anyMatch, noneMatch
  • FindFirst, findAny
  • Collect – collect data from stream and return something that isn’T a stream such as map of lists, min, collection or join strings with delimiter
java.util.function package
  • Function<T,R>  t input, r output
  • Predicate <T> – t input, boolean output
  • Consumer <T> a t input no output
  • Supplier <T> – no input, t output
  • BinaryOperator<T> – take two T’s an inout and returns one as output
and many more
Options
  • Optional<Long> o -returns an object that may or may not hold a long
  • o.get() to actually get the long
  • Throws exception if no value
  • o.ifPresent to check if there
  • o.orElse(a) – returns from get or hard coded value if not
Use carefully
New patterns
  • Try to pass streams around   Don’t need to keep converting to list.  Limitations on streams are not being able to go backwards and forwards and that can’t serialize.
  • Can now put static methos on interface
    comparator.comparing(lambda). ThenComparing(Comaprator.naturalOrder())

Multi core

B -> b.parallel().count() – can take advantage of multiple cores – can chop up work – uses work stealing – breaks up into smaller pieces so caget work from busy neighbors