Category Archives: Java 8

The Rise and Fall of Scala

There seems to be a consensus in the Java community that the Scala programming language is already on the decline. I consider this a pity because I always enjoyed programming in Scala. Actually, I even started this blog to support alternative JVM languages like Scala. But the market has decided differently. Moshe Kranc has written an excellent analysis about the rise and fall of Scala. I found Moshe’s article interesting enough to summarize it and to add a couple of thoughts of mine.

Before I start

However, I’ve also read some of the 169 comments to Moshe’s article, so I’d like to add a few words. First of all, I’m really fond of the Scala language. I’m not trying to write an anti-Scala article. Quite the contrary. I’m following the fate of Groovy and Scala for at least ten years now, and I’m still puzzled why the industry doesn’t adopt one of these languages. In many aspects, both languages are clearly superior to Java.
Continue reading

TypeScript and ES2016 Decorators vs. Java Annotations

Consider this TypeScript snippet. It’s a very simple Angular2 component. It looks almost like a Java class, doesn’t it?

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

In particular, the @Component looks like a Java annotation. In fact, it plays the some role as a Java annotation. It tells the Angular2 framework that this class is not an ordinary POJO, but something special. It’s a component, one of the building blocks of Angular.

Striking similarity

That’s exactly the same thing I already knew from the Java world. @Named converts a POJO into a CDI bean. Sometimes Java annotations even have the same fancy curly braces syntax:

@ResourceDependencies({ 
  @ResourceDependency(library = "bsf", name = "js/datatables.min.js", target = "body"),
  @ResourceDependency(library = "bsf", name = "css/datatables.min.css", target = "head")
})
public class DataTable extends UIData {}

So why do the JavaScript and TypeScript communities insist on calling their annotations “decorators”?

Decorators decorate!

The answer is simple: Decorators are called decorators because that’s what they are. You can use them as annotations. But in reality, they are function calls. The Angular2 framework contains a function called Component() that takes a function as a parameter and returns another function. The @ of @Component tells TypeScript and EcmaScript 2016 to call the Component() function and to pass it the function after the decorator. Usually decorators are used to add functionality to a function.

AOP

Does this ring a bell? Exactly – that’s more or less the same as aspect oriented programming. In fact, AOP is one of the classical use cases of Java annotations. Just think of @transactional. This annotation surrounds a method with the glue code needed to execute it in a transaction. In other words, it adds some code before executing the method (opening a transaction) and it adds code after the method (committing the transaction, or rolling it back).

Oops!

Making the @ symbol an alternative way to call functions is a very elegant way to implement both static annotations and AOP. Plus, it should be possible to pass variables as additional parameters. In Java, annotations only support constants that can be resolved a compile time, and every once in a while, that’s a nuisance.

In hindsight, it’s hard to understand why the Java team added simple annotations instead of full-blown decorators to Java 5. I suppose they didn’t want to add a complex multi-purpose tool. Annotations can be used for exactly one purpose. They resemble a comment. They rely on a framework to be useful. This framework can be the editor, the compiler or the runtime environment. Only a few years later the JavaScript world showed how useful decorators are.

Can decorators be added to Java?

Sure. Java 8 introduced default methods. So we could define a default method in an annotation class and execute it when the annotated method is called. We’d have to consider a couple of corner cases, though. Annotations can be applied to classes, static fields, class attributes and method parameters. We’d have to define useful semantics for each of these corner cases. But that’s not a big deal.

Wrapping it up

However, I don’t think this will ever happen. Annotations have become such an important part of the Java world it’s unlikely anybody takes the risk. So, for now, we can only marvel at the way the language designers took the syntax of the annotation and converted it into something even more useful. By the way, the flexibility of the JavaScript language allows for some tricks Java developers can only dream of. Only – Java applications tend to be a lot bigger than JavaScript applications, so this dreams would quickly turn into a nightmare. Nonetheless, the article I’ve linked in the “dig deeper” section is very interesting, and it’s full of surprises – at least for a programmer like me spending most of their day in the Java ecosystem.

Dig deeper

Exploring EcmaScript 2016 decorators in detail

Sparkling Services

WebServices and REST services have come a long way in Java. Nowadays, it’s very easy to create a webservice. Basically, it’s adding an annotation to a method. All you need is a servlet container, such as Tomcat. But then, configuring and running a servlet container isn’t really simple. Chances are you think it’s simple, but that’s because most Java programmers have been using application servers for years. They already carry everything they need in their toolbox. But from a newbie’s point of view, things look a little different.

Spark is a nice alternative making it really easy to write a REST service:

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

That’s all you need to implement a web server that serves a single REST service. Start the program, open your browser and enter the URL to test your REST service:

http://localhost:4567/hello

Notice that this is a main method. You don’t have to deploy a war file. Instead, Spark follows the idea popularized by Spring Boot: it embeds Jetty in a jar file. When I tested the code, Spark took virtually no time to start. That’s the nice thing about embedding Jetty: it has a really small footprint. I started to use an embedded Jetty for my web applications years ago. It’s a really fast alternative if you don’t need a full-blown application server.
Continue reading

Type Erasure Revisited

You can’t beat type erasure, they say. Information about generic Java data types is lost during compilation, and there’s no way to get it back. While that’s absolutely true, Mahmoud Ben Hassine and I found a tiny loophole which allowed us to improve Mahmoud’s jPopulator framework tremendously. Under certain circumstances, it’s possible to find about the type which is supposed to be erased. So jPopulator is able to populate not only simple beans, but also complex generic data types.

Mahmoud agreed to write an article about the ups and downs of our investigation. You’ll see it wasn’t exactly easy-going. Along the way, you’ll learn about the loophole allowing us to beat type erasure.
Continue reading

Java 8 Named Method Parameters

I was very surprised when I read Adam Bien’s blog post on named parameters in Java 8.

Named parameters? Well… not quite. At least not the kind of named parameters we know from languages such as Visual Basic, Groovy and many others. But it turned out to be an interesting read nonetheless. The article is about the Java 8 improvements of the reflection API.
Continue reading

Newsflash: Java Decompilers

Nowadays everybody seems to pull their libraries from Maven Central, which encourages to upload both the binaries and the source code of a library. Most developers follow the guidelines, so nowadays it has become painless to read the source code of the open source libraries you use. Debugging such a library usually is pretty simple. You don’t have to look for the source code, it’s just there.

Still, every once in a while you’re looking for a bug occurring in a library without source code. In such a situation a Java decompiler comes in handy. It analyzes the Java byte code and tries to reconstruct the original source code.

This article covers three decompilers in some (limited) detail and provides a link to an article covering a dozen more decompilers.
Continue reading

AngularFaces 2: Even Better Steroids for JSF

Fork me on GitHubAngularJS and other fancy Javascript frameworks stir up the Java world. The Java world has been dominated by server side framework for more than a decade now. Times they are changing. Now everybody’s moving to the client side. The server’s reduced to a faint memory, such as a REST service.

Everybody? Not quite. A lot of developers want to steer a middle course. That’s AngularFaces for you.

By the way, the interest in AngularFaces is tremendous. The AngularFaces announcement has become the second most read article of beyondjava.net, being read a hundred times each day.

So I decided AngularFaces needs a strong grounding. You know, the first version hadn’t really been designed carefully. It just happened. Originally it was just a little experiment. Granted, it works fine, but it’s difficult to add new features to it. The second version is a complete re-write designed for the future. AngularFaces 2.0 has a lot of advantages over it’s predecessor.

And the nice thing about AngularFaces 2.0 is it’s already available as a preview version on GitHub.

Update Sept 16, 2014
Actually, the final version of AngularFaces 2.0 looks completely different from the AngularFaces 2.0 I envisioned four months ago. It doesn’t define components, it’s a plugin to existing components. In other words, it adds functionality to most components of Mojarra, MyFaces, PrimeFaces and probably (although I haven’t run a test yet) to most other JSF widget libraries. Nonetheless I think the ideas described in this article are good ideas worthy to be implemented. The AngularFaces widgets have moved to a project called AngularFacesWidgets.
Have a look at the tutorial at AngularFaces.com if you’re interested in AngularFaces 2.0 and above.
Continue reading

Recent Improvements of Java’s String Implementation

Three days ago, I wrote an article about Strings in Java 8. I claimed they’d rewritten java.lang.String from scratch, supporting a 64 bit encoding that can be processed by the processor’s FPU. Of course, it was an April prank. So I was pretty surprised to learn there really are improvements of Java’s string implementation. They aren’t even subtle.

Java 7 Update 6 introduced a new implementation of java.lang.String that’s better suited for large numbers of Strings. As you may or may not know, the former implementation had been designed with optimizing the substring() method in mind. It was super-fast because it didn’t copy the characters of the substring. Instead it created a new pointer to the old String. Sometimes this prevents effective garbage collection, and it makes the intern() function extremely expensive.

So they opted to implement a new version that’s simpler. As a result of the new implementation substring() has to copy the character array. In the age of multi-gigabyte PCs and servers that’s more efficient than trying to save a few bytes.

In Java 7 they also abandoned 8-bit Strings. Now 16-bit Unicode strings are always used. That’s funny because it almost matches my April prank, where I claimed they abandoned the 16-bit character encoding in favor of 64-bit encoding. I wonder if java.lang.String makes use of the FPU?

Read the full story at Attila Balazs article on the state of strings in Java.

Java 8: Major Speed Boost by Overhauled String API

April 1st, 20141 2 Java 8 is out for a week or two now, and we all have been puzzled by the tremendous speed improvements of Oracle’s newest coup. String operations in particular have improved a lot. It’s time to look into the guts of Java and to analyze what’s going on.

Along the way, I also found out why Pattern.compile() has been deprecated in Java 8. Please stop using it. It’s a big performance penalty.

It took me a while to find out. Only when I looked into the byte code generated by Java 8, I realized what has happened. Oracle has overhauled its String implementation. Actually they have rewritten it from scratch. They need to retain the backward-compatibility, so it wasn’t that easy to see the trick: they abandoned 16-bit Unicode, replacing it by a more modern encoding. A major step to a more memory-efficient design! The Java community has been longing for this move since ages.
Continue reading

  1. Yes, this was this year’s April fool’s hoax.
  2. But read my follow-up article to learn about the real improvements of the string implementation.

Your IDE Supports Java 8 From Day One

Yesterday the lambda revolution has been released: Java 8 is there. Java programmers can finally benefit from closures, function pointers and multiple inheritance. Or rather, limited versions of these features that are almost as useful. BeyondJava.net has a series of articles on the topics (see method references, lambda expressions, functional programming and closures vs. lambdas). There’s even an interesting (and very unique) approach to type inference in Java 8: target typing.

For the first time in Java history each of the major IDEs support Java 8 from day one. In earlier times we had to wait roughly half a year until Eclipse supported the new version of the language. This time, there’s a feature patch you can install in Eclipse 4.3.2 (aka Kepler SR2). To install it, click “Help > Install new software”, enter the URL http://download.eclipse.org/eclipse/updates/4.3-P-builds/ into the “Work with” field and proceed the usual way.

According to netbeans.org NetBeans 7.4 also supports Java 8. And of course IntelliJ IDEA does: I tried it more than a year ago with a preview version of Java 8, and the IDE supported lambdas, method references and defender methods flawlessly.

An interesting question is the future of Java. Which impact will lambdas have on our programming style? Here’s an early assessment: when I write in other programming language such as Groovy, Scala or Dart, I use closures a lot. My programming style changes considerably. In general, programs become shorter and more readable. I doubt this will happen to Java. There’s no doubt Lambda expression fill a gap (almost a gaping chasm, to tell the truth). Framework programmers like me were suffering from not being able to pass algorithms as parameters to methods. This has become possible at last. Many features that have been solved by sophisticated approaches can now be solved by simple methods. For instance, until Java 7 you needed annotations and AOP to implement transaction in a decent way. With Java 8, a simple method does the trick just as well. Nonetheless, my first impression is Java will remain a non-functional programming language until Oracle adds more syntactic sugar to the language.

Is Java 8 a Functional Programming Language?

I’m pretty excited about Java 8 most important feature: lambda expressions. I can think of so many ways to utilize them I can hardly wait until I can use Java 8 in vocational life. Lambdas stem from the world of functional programming languages, so obviously Java 8 is a functional programming language. It’s in the same league as languages like LISP, Clojure and Scala.

But wait – is this true?

Some ten months ago I used Java 8 to write a Mandelbrot set plotter. No matter how hard I tried the program wouldn’t become functional. It was just a good old procedural program using a couple of lambda expressions. It can’t be the algorithms fault: Mandelbrot sets are all about functions. So what is it that stops Java 8 from being a functional language?
Continue reading

The Hidden JavaEE Gem: Lambda Expressions With Java 7

This morning Adam Bien has a surprising story: While the majority of the Java world is impatiently waiting for Java 8’s closures, JSF programmers can use lambda even today. All you need is EL 3.0. Even more, every Java 7 programmer can use lambda expressions by simply including the class EL library to the classpath:

<dependency>
	<groupId>org.glassfish</groupId>
	<artifactId>javax.el</artifactId>
	<version>3.0.0</version>
</dependency>

Of course the code can’t be as concise as real Java 8 code because you have to use a method that’s passed the closure as a String. The String also makes it difficult to use the feature in real-world problems. You’d have to convert the object you want to operate the closure to a String first. Nonetheless the code looks surprisingly simple and elegant:

public class LambdaDemo {

    public void init() {
        ELProcessor  cut = new ELProcessor();
        Object result = cut.eval(
               "[1,2,3,4,5,6,7,8]
               .stream()
               .filter(i->i%2 == 0)
               .map(i->i*10)
               .toList()");
        System.out.println("Result: " + result);
        result = cut.eval(
               "[1,5,3,7,4,2,8]
               .stream()
               .sorted((i,j)->j-i)
               .toList()");
        System.out.println("Result: " + result);
    }
}

Read the full story at Adam Bien’s Blog.

Closure Scope – Why Java 8 Prefers Simple Lambda Expressions

Did you ever wonder why the Java 8 programmers chose to implement simple lambda expressions instead of full-blown closures? What’s so difficult about simple programs like this one?

int faculty=1;
5.times{int factor -&amp;amp;amp;amp;amp;gt; factor *= faculty}
println faculty

Let’s have a close look at closure scope.
Continue reading

On Goroutines, Coroutines and How to Simulate Them in Java 8

Google’s Go language offers a nice idea how to run processes concurrently. They called it “goroutine” – clearly an allusion to coroutine, but they felt they made something new, so they gave it a new name.

The idea is very simple. Every method preceded by the word “go” is run concurrently. The Go language adds an elegant concept to define and run anonymous functions (similar to the way Javascript does). The last building block is the possibility to define variables that can roughly compared to futures at stock exchange: They don’t exist when you define them, but they are guaranteed to exist when you need them.

Real world futures (if they can be called like this, given modern stock exchange is run almost entirely in its own virtual reality) can become very expensive for the seller. They are forced to deliver in time, no matter what the costs are. In contrast, the Go language simply blocks the access to the future until it’s there. If you’ve already used Java’s Futures, you know the idea.
Continue reading

Java 8 Lambdas Seem to be Allowed to Contain Defender Methods

I just got aware how much Java 8’s lambda expressions differ from closures.

Traditionally, closures are very short pieces of code. In many aspects closures are a short-hand notation for methods (plus the extended variable scope). Java 8 lambdas are full-blown classes – including inheritance, methods and everything else.

Continue reading

Java 8’s Optional Type, NullPointerExceptions and the Elvis Operator

Sooner or later every Java programmer is maddened by the notorious NullPointerException. Not only Java programmers, by the way. Probably every JVM programmer is suffering from the problem, and many other languages know similar problems.

What makes the NullPointerException so annoying is the fact is essentially a NotImplementedYetException in disguise.

Continue reading

Java 8 – Catalyst for a Superior Language?

These days I’ve read two language-related stories at Lavalobby. The first story I read matched my own experience on the topic. It has also an refreshingly optimistic air. Obviously, the author believes in progress. The second article also had a lot of ideas matching my experience.

Thing is, both articles contradict each other.

While the first article expects Java 8 to be merely a catalyst giving rise to more innovative languages, the second article insists that Java is here to stay. It the programming world’s lingua franca, and it won’t be replaced by a fancy new language.

Both articles have a point.
Continue reading

Java 8: PermGen Space Errors Abolished – But…

One of the nice things about Java 8 is the end of the OutOfMemoryError caused by depleted PermGen Space. These errors are especially nasty, and you can’t avoid them. Once your using one of the more interesting libraries – be it a database driver or Log4J – your program is infested (see me article on the topic).

But… well, if Pierre-Hugues Charbonneau is right, little is won. The error has simply been replaced by another OutOfMemoryError. The problem itself has yet to be solved. Read the full story at Pierre-Hugues Charbonneau’s web site.

By the way, if you’re still using Tomcat 6, there is a partial solution: I’m told Tomcat 7 does a much better job on freeing PermGen space than its predecessor.

Aparapi: Run Java Applications on Your Graphics Accelerator Card

What could you achieve if you had a thousand CPU cores at hand? Actually, you probably have. All you need a dedicated graphics accelerator card. For example, my Radeon™ 6870 GPU has 1120 stream processors and delivers up to 2.000 GFlops of single precision floating point performance. That’s at least 10 times the performance of the i7 CPU in my computer. Wouldn’t it be nice to unleash this power?

Aparapi allows Java programmers to do so. If you’ve got the right type of problem, that is.
Continue reading

JavaFX and GroovyFX: Two Frameworks You May Have Missed

Like most Java programmers I’ve gradually become a web developer during the last years. In a way, that’s strange: most projects don’t deal with the internet. It’s a pity, too. Browsers used to be dedicated tool for the internet, so it’s hard to meet the demands of an full-blown desktop application. It’s a real pain to integrate Excel sheets seamlessly into a web applications. So what about desktop GUI frameworks? There’s an interesting Java framework you most probably know by name without ever having looked at: JavaFX. It makes for nice-looking GUIs, and it matches Java 8 pretty good. Combine it with GroovyFX to get GUI classes that strongly resemble JSF files. Without suffering from JSF’s inherent complexity.
Continue reading