Java 8, Three Months In: Lambdas, Streams, and a JavaScript Engine

Java 8, Three Months In: Lambdas, Streams, and a JavaScript Engine

7 min readarticlejavajava-8nashorn

Three months ago, on March 18, Oracle finally shipped Java SE 8. I say "finally" because half of it was originally promised for Java 7. That was 2011. In software years, 2011 is roughly the Bronze Age.

Every release I tell myself the same thing: this time, write a short post. Crisp, digestible, read in one sitting. It never happens. It cannot happen. Because I care about you, and there is too much to tell. 🤓

So here is everything that actually matters in Java 8, after three months of living with it. If your attention span gives out halfway, the summary is simple: upgrade, learn lambdas, and delete every Calendar you can find.

☕ The Big Picture

Java 8 is the biggest change to the platform since Java 5 in 2004. To put 2004 in perspective: Gmail was invitation-only, the iPhone did not exist, and "cloud" meant weather.

The first patch update (8u5) arrived in April, the major IDEs were ready on day one, and the Spring crowd had been preparing since December. The "Java is dead" crowd, now in its second decade of uninterrupted mourning, will have to wait a little longer.

λ The Headliner: Lambdas

JSR 335 has been "almost done" for so many years that seeing it actually ship feels like a prank. And yet here it is:

// Java 7
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.compareToIgnoreCase(b);
    }
});

// Java 8
names.sort((a, b) -> a.compareToIgnoreCase(b));

Six lines in, one line out. Your keyboard will live longer.

The clever part is what they did NOT do. No new type system, no function types bolted on. A lambda is simply an instance of an interface with one abstract method, and the compiler figures out which one from context. That single decision made Runnable, Callable, Comparator and twenty years of "SAM" interfaces lambda-ready overnight. Say what you will about committees. This one earned its coffee.

The new java.util.function package supplies the standard shapes (Predicate, Function, Consumer, Supplier), the @FunctionalInterface annotation keeps your interfaces honest, and method references collapse things even further:

names.sort(String::compareToIgnoreCase);

🌊 Streams

Lambdas alone would be a party trick. The Streams API (java.util.stream) is where they pay rent:

List<String> shortNames = names.stream()
        .filter(n -> n.length() < 6)
        .map(String::toUpperCase)
        .sorted()
        .collect(Collectors.toList());

You describe WHAT you want, not HOW to loop. After twenty years of telling Java exactly how to walk, simply saying "over there, please" takes some getting used to. Streams are lazy, so nothing moves until a terminal operation like collect pulls data through, and no intermediate collections clutter the heap along the way.

There is also parallelStream(), which puts the fork/join framework to work on all your cores. Measure before you brag, though. For small lists it is a Ferrari on a grocery run.

🔀 Default Methods

The quiet enabler of all this: interfaces can now carry method bodies. That is how Iterable gained forEach and List gained sort without breaking every implementation written since 1998:

names.forEach(System.out::println);

If you just felt a disturbance, that was a million computer science professors crying out in terror. Relax. The conflict rules are explicit: class wins, then the most specific sub-interface, and if all else fails you override and pick a side with InterfaceName.super.method(). Multiple inheritance of behavior, with the diamond problem defused in advance. A careful compromise, and I mean that as praise.

📦 Optional

A small class with a big idea: make "might be absent" part of the type signature instead of a null landmine waiting in your codebase:

String city = Optional.ofNullable(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .orElse("Unknown");

It is deliberately minimal. Not serializable, no fields, clearly meant for return values. Use it as a field and Brian Goetz will find you.

🕰 Date and Time

JSR 310, led by Stephen Colebourne of Joda-Time fame, finally retires the old Date/Calendar duo. Mutable, not thread-safe, and months that start at zero. Whoever approved zero-indexed months owes this industry an apology and several thousand developer-years.

LocalDate today = LocalDate.now();
LocalDate eclipseLuna = LocalDate.of(2014, Month.JUNE, 25);
long daysLeft = today.until(eclipseLuna, ChronoUnit.DAYS);

ZonedDateTime inLondon = LocalDateTime.of(2014, Month.JUNE, 25, 14, 30)
        .atZone(ZoneId.of("Europe/London"));

Immutable. Thread-safe. Readable. Pick three. For the first time in Java history, you can.

🎭 Nashorn: JavaScript on the JVM

Here is the sleeper feature. Nashorn replaces the ageing Rhino as Java's embedded JavaScript engine, rebuilt from scratch on invokedynamic, with Oracle claiming performance gains of several times over its predecessor. It comes with a command-line tool called jjs and plugs into the standard scripting API:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from JavaScript on the JVM')");
$ jjs
jjs> var list = java.util.Arrays.asList('lambda', 'streams', 'nashorn')
jjs> list.forEach(function(e) { print(e) })

JavaScript calling Java, Java calling JavaScript. Useful for scripting plugins, test automation, and letting your front-end colleague prototype against the backend without learning what a Maven is.

Meanwhile, in the other JavaScript

You cannot discuss server-side JavaScript in 2014 without mentioning Node.js. Node is a separate runtime built on Chrome's V8 engine, current stable 0.10.x (0.10.29 as I write this), and its whole religion is the event loop: one thread, non-blocking I/O, thousands of concurrent connections. Java developers hear "one thread" and instinctively reach for a thread pool. Resist.

The model shines for I/O-heavy work: real-time apps, chat backends, API gateways. PayPal rebuilt part of its account stack on Node last year, LinkedIn has run its mobile backend on it since 2011, and Walmart served Black Friday traffic on it. For CPU-heavy number crunching, look elsewhere. And the npm registry, growing at a frankly alarming pace, does the rest.

The interesting part for us: the two worlds are converging. Oracle's Avatar.js, from the open-sourced Project Avatar, reimplements the Node API on Nashorn. Red Hat's Nodyn is chasing the same goal, and the polyglot vert.x 2.x already brings the event-loop model to Java, JavaScript, Ruby and Groovy over a shared event bus. Node-style concurrency with JVM operations and tooling. Watch this space.

JavaScript on the JVM, serving HTTP. A 1995 press release somewhere is feeling deeply vindicated.

🔧 Under the Hood

The less glamorous items, each worth knowing:

  • PermGen is gone. Class metadata moved to native memory (Metaspace). Fewer midnight OutOfMemoryError: PermGen space pages. Your on-call rotation says thank you.
  • Compact Profiles: three subset footprints of the Java SE API. A down payment on the modularity we keep being promised.
  • Type annotations (JSR 308): annotations wherever types appear, enabling build-time checkers like @NonNull.
  • Repeating annotations: declare the same annotation twice, no wrapper-class dance.
  • java.util.Base64 finally standardizes encoding. Yes, in 2014. Welcome.
  • CompletableFuture for composable async pipelines, StampedLock for optimistic reads, Arrays.parallelSort for a free multicore sort.
  • The JDBC-ODBC bridge has been removed. It is survived by no mourners.

Extra tidbit: the Java installer still proudly claims Java runs on 3 billion devices. It neglects to mention that half of them are currently showing an update balloon.

🧰 Tooling and Ecosystem

Tool support landed fast. IntelliJ IDEA 13.1 shipped in March with full Java 8 support, and it will convert your anonymous classes into lambdas as you browse old code. Rude, but useful. NetBeans 8.0 launched the same day as the JDK, and Eclipse users get theirs with 4.4 (Luna), due June 25. Later this month. Patience.

On the framework side, Spring Framework 4.0 arrived in December with Java 8 in mind, so lambdas slot neatly into its callback-heavy APIs, and Spring Boot 1.0 went GA in April. The ecosystem was clearly sitting by the door, waiting.

🔭 What Comes Next

Oracle's roadmap points to Java 9 around 2016, with Project Jigsaw and the long-promised module system as its centerpiece. Jigsaw has been "two releases away" for so long it qualifies as folklore at this point. This time, surely.

Three months in, my verdict is boring in the best possible way: upgrade. Let IntelliJ refactor a few anonymous classes, stream a collection or two, and take LocalDate out for coffee. You will not want to go back.

Hoping to compile again soon. 🙋‍♂️