Project Nashorn: JavaScript’s Second Chance on the JVM

Throughout 2012, JavaScript seems to be solving problems across the industry, causing some justifiable hype across a number of libraries and frameworks.  Oracle’s Project Nashorn  was recently announced, due for release with Java 8 in late 2013, which will allow JavaScript to be embedded in Java applications and to develop standalone JavaScript applications.

It makes sense that the JVM maintains it’s relevance by providing an improved JavaScript engine: there have been indications that performance is up to five times faster than the current Rhino implementation and the engine footprint is five times smaller.

We spoke to Henrik Stahl, senior director of Java product management at Oracle to find out more.

DZone: Where did the motivation for Nashorn come from?  

Henrik Stahl: Oracle recognizes that multi-language support is important to Java

 

  • The Rhino engine currently used is dated and not architected together with the JVM
  • Writing a new engine allows us to validate the Invokedynamic (JSR-292) feature in JDK 7, leverage all new language and JVM features in JDK 8, as well as provide a seamless way of using Javascript and Java code in the same program.

DZone: How long have Oracle been working on it internally?

Henrik: We have been working on Nashorn for the past year and a half.

DZone: Was it originally for any other purpose or products? 

Henrik: 
No. The goals have remained the same since the project’s inception, although we have found ways to use it that we hadn’t originally anticipated; such as using it as a backend for the Javascript development and debugging features in Netbeans.

DZone: How much of Nashorn is already complete?

Henrik: The Nashorn engine is passing all ECMAScript 5.1 compliance tests.  Early access users have been able to switch their application from Rhino to Nashorn without major issues.

 DZone: And what still needs to be added?

Henrik: The team is currently focused on robustness and performance as well continuing to evaluate potential JVM optimizations.  The team is also starting to explore support for upcoming ECMAScript 6.0 features.

DZone: Why do you think that Nashorn will be more successful than Rhino, the previous JS implementation on the JVM?  

 

  • Nashorn significantly outperforms Rhino, and the gap will increase even more as we now move focus from spec compliance and stability to performance
  • Nashorn implements a new meta-object protocol that simplifies calling Java APIs from JavaScript, and enables seamless interactions between JavaScript and Java.
  • Nashorn enables infrastructure providers to consolidate their JavaScript and Java workloads on single virtual machine technology, and leverage the JVM management, debugging and profiling capabilities.

More Focussed Debugging Now Available With Chronon 3

Already considered as quite an impressive tool, Chronon 3  was released recently, bringing even more features and improvements.  Top of the list are the performance improvements; and the improvements delivered cannot be understated. You won’t need to worry about running out of memory with Chronon anymore.

I asked Prashant Deva, Chronon’s founder, about how exactly they got the improvements. Because of the amount of feedback the team were getting about OutOfMemory errors, Chronon 3 was completely re-architected from the ground up. Obviously, this process took a lot of time, and is the reason there was a long time between the previous release and Chronon 3.

Prashant gave me an amazing insight into how Chronon recorder works in the background:

If you were to look at the source code of a computer program, especially a single threaded program, you will notice that you can pretty much predict what a program is going to do.  Sure the program will have branches and loops but those brances will be dependent on the values of some object in memory and if you know its value, then you can predict the flow.

Chronon 3 Recorder is based entirely on this idea of ‘predictions’. The Recorder reads the bytecode of your application and does a static analysis of your code.
From this analysis, it creates a bunch of ‘predictions’, about how your program will execute.
An example of a prediction might be :
Call bar() at line 46 in Foo.java.
Then it monitors the execution of your program.
It keeps adjusting the ‘prediction’ data structures to account for what your program acutally does.
Then the recording data that is generated is really just how much your program differs from these predictions.

For example, in the case of the earlier prediction:
Lets say you have 2 threads:
Thread 1 :
Execution matches prediction completely
Calls Foo.bar() at line 46 in Foo.java.
In this case, no recording data is generated, since the prediction is matched 100%.

Thread 2
Calls overloaded method Foo2.bar() at line 46 in Foo.java.
In this case, the prediction data here will be modified, for this thread only, to account for the fact that 2 methods may be called here – Foo.bar() and Foo2.bar()
Then only 1 bit, is saved which tells that Foo2.bar() is the method that was acutally called.

In previous versions of Chronon these method calls would have generated over 128 bits of data per call. In Chronon 3, they generated 1 bit or no data at all.
Thus you can get a glimpse of what a huge performance benefit this is.

The other thing we have done is to make use of non-heap memory as much as possible. So most of the recording data, and things like compression, etc are all done natively and dont impact the heap of your java application and thus dont impact the GC.

Another new feature you’ll want to try out is  Per Thread Time , allowing you you to focus on specific thread instead of the entire system. You get to see this in the Stack view too. Focus is everything – if you know of a troublesome thread, you can forget about the rest.

Also you can split recordings at any time on the server, instead of waiting for the Recording Server to split them for you.

 Chronon have offered JavaLobby readers a special 10% discount to use when purchasing personal licences of Chronon, using the JAVALOBBY coupon code

In the future, you can expect closer releases of Chronon, where the prediciton plug-in model will be continuously added to. The more predictions that Chronon provide will improve the performance.

As always, Chronon are listening to what users want in order to define the feature set for the next release. You can expect to see support for Java Collections sometime soon, another much requested feature, while the Recording Server will have new features to help with Ops and Application Monitoring

New Java Update Introduces JavaFX Scene Builder

Oracle have been busy – they have released the latest update for Java 7 and JavaFX 2.2, introducing the first release of JavaFX Scene Builder. There’s good news for developers on Mac OS X, as they will have full availability of the release, and get auto-updates at the same time as those on Windows platforms.

Along with the good news for Mac owners, there is now a JDK for Linux on ARM v6/v7 so that you can get Java running on your Raspberry Pi.  Henrick Stahl has more details about the ARM port.

Is the Oracle JDK port to ARM available in OpenJDK? No, and we are not planning on open sourcing it at this point.
I own a Raspberry Pi/BeagleBoard/PandaBoard. How do I get Java running on it? Make sure that you use a Linux distribution that uses the softfloat ABI, then download and install the Oracle JDK on it.

JavaFX is now fully integrated into the Java SE implementation from this release. There is also the essential addition of multi-touch support, and an application packager to make distributing new bundles easier.

The Scene Builder provides a visual layout tool to create your JavaFX user interfaces.  
In other news, JavaOne attendees will be treated to performances by Pearl Jam and Kings of Leon at the Appreciation Event this September.

The Most Popular Language This Month Is….

The most popular language of this month? Well it depends which source you use. For example, I checked out the TIOBE index as well as the top language used in GitHub projects. Would you be surprised that Java was not number 1 on either listing?

Now, I never take these language popularity things too seriously. More than likely, the language you’re using at work isn’t the cool language of the day. But it gives a good indication of what languages might be worth learning, if you have the time.

TIOBE Index – C Reigns Supreme

On the TIOBE index, where Java has been number one for a very very long time, C has taken it’s place at the top. Yes, C!

Don’t worry if you’re confused right now looking at this – I don’t get it either! It’s obvious that Objective-C continues to grow more popular. But JavaScript looks a bit low on this index, especially when you consider the results I found at GitHub

GitHub  – Everybody Loves JavaScript

I guess the GitHub ratings make more sense, considering you can’t move in GitHub without bumping into a JavaScript project. Every other language has a reasonable showing. Compare Java to C and there’s not much in it.

Some Better News For Java Developers

I didn’t have to go too far to find some good news for Java developers. RoleConnect, an Irish company that connects contractors with employers ran some analysis on what skills are most in demand right now. According to the team there, there’s still a huge interest in Java/J2EE and Spring developers.

So, three different indices and it’s no clearer what the most popular language really is. Is there a definitive way to measure this statistic? Or is it just all too subjective?

Design Patterns Uncovered: The Decorator Pattern

Today’s pattern is the Decorator pattern, which allows class behaviour to be extended dynamically at runtime.

Decorator in the Real World

The concept of a decorator is that it adds additional attributes to an object dynamically. A real world example of this would be a picture frame. The picture is our object, which has it’s own characteristics. For display purposes we add a frame to the picture, in order to decorate it. You’re probably already familiar with the concept of wrapper objects, and in essence, that is what a Decorator is.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Decorator Pattern

The Decorator is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Decorator provided in the original Gang of Four book on Design Patterns states:

Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviours

Traditionally, you might consider subclassing to be the best way to approach this – but there will be cases that subclassing isn’t possible, or is impractical. This leads us to the Open/Closed Principle: classes should be open for extension, but closed for modification. This is a good principle to keep in mind, as it keeps your class stable, but leaves it open for extension if someone wants to add behaviour.

Let’s take a look at the diagram definition before we go into more detail.

The Component defines the interface for objects that can have responsibilties added dynamically, and the ConcreteComponent is simply an implementation of this interface. The Decorator has a reference to a Component, and also conforms to the  Component interface.  This is the important thing to remember, as the Decorator is essentially wrapping the Component. The ConcreteDecorator just adds responsibilities to the original Component.

Would I Use This Pattern?

The Decorator pattern should be used when:

  • Object responsibilities and behaviours should be dynamically modifiable
  • Concrete implementations should be decoupled from responsibilities and behaviours

As mentioned in the previous section, this can be done by subclassing. But too much subclassing is definitely a bad thing. As you add more behaviours to a base class, you will soon find yourself dealing with maintenance nightmare, as a new class is created for each possible combination. While the decorator can cause it’s own issues, it does provide a better alternative to too much subclassing.

So How Does It Work In Java?

You’ll see decorators being used in Java I/O streams. Stream classes extend the base subclasses to add features to the stream classes.

In our example, we’ll use emails to illustrate the Decorator.

First we have an email interface, which has a getContents method:

public interface IEmail
{
   public String getContents();

}

And we’ll provide a concrete implementation for use:

//concrete component
public class Email implements IEmail
{
   private String content;

   public Email(String content)
   {
      this.content = content;
   }

   @Override
   public String getContents()
   {
      //general email stuff
      return content;

   }

}

Now we’ll create a decorator which will wrap the base email with extra functionality. We’ll model this as an abstract class, and maintain a reference to the base email.

public abstract class EmailDecorator implements IEmail
{
   //wrapped component
   IEmail originalEmail;

}

Let’s say that emails that leave the company internal server need to have a disclaimer added to the end. We can just add in a decorator to handle this:

//concrete decorator
public class ExternalEmailDecorator extends EmailDecorator
{
   private String content; 

   public ExternalEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = addDisclaimer(originalEmail.getContents());
      return content;
   }

   private String addDisclaimer(String message)
   {
      //append company disclaimer to message
      return  message + "\n Company Disclaimer";
   }

}

And if we wanted to create secure, encrypted messages, we could use another decorator:

//concrete decorator
public class SecureEmailDecorator extends EmailDecorator
{
   private String content; 

   public SecureEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = encrypt(originalEmail.getContents());
      return content;
   }

   private String encrypt(String message)
   {
      //encrypt the string
      return  encryptedMessage;
   }

}

So, if our email sending client detects this message is going outside the company, we can invoke the appropriate decorator before sending:

public class EmailSender
{

   public void sendEmail(IEmail email)
   {
      //read the email to-address, to see if it's going outside of the company
      //if so decorate it
      ExternalEmailDecorator external = new ExternalEmailDecorator(email);
      external.getContents();
      //send 

   }
}

Watch Out for the Downsides

Overuse of the Open/Closed principle can lead to abstract and complex code. This principle should really only be used in places where code is least likely to change.

The Design Patterns book does point out a couple of disadvantages with this pattern. Decorators can lead to a system with a lot of smaller objects that will look similar to a developer and introduce a maintenance headache. Also, the Decorator and it’s enclosed components are not identical, so tests for object type (instanceof) will fail.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Proxy Pattern

Today’s pattern is the Proxy pattern, another simple but effective pattern that helps with controlling use and access of resources.

Proxy in the Real World

A Proxy can also be defined as a surrogate. In the real work a cheque or credit card is a proxy for what is in our bank account.  It can be used in place of cash, which is what is needed, and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – controls and manage access to the object they are “protecting”.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Proxy Pattern

The Proxy is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Proxy provided in the original Gang of Four book on Design Patterns states:

Allows for object level access control by acting as a pass through entity or a placeholder object.

So it’s quite a simple concept – to save on the amount of memory used, you might use a Proxy. Similarly, if you want to control access to an object, the pattern becomes useful.

Let’s take a look at the diagram definition before we go into more detail.

As usual, when dealing with design patterns we code to interfaces. In this case, the interface that the client knows about is the Subject. Both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject without going through the Proxy. It’s quite common that the Proxy would handle the creation of the RealSubject object, but it will at least have a reference to it so that it can pass messages along.

Let’s take a look at this in action with a sequence diagram.

As you can see it’s quite simple – the Proxy is providing a barrier between the client and the real implementation.

There are many different flavours of Proxy, depending on it’s purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.

You’ll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.

Would I Use This Pattern?

This pattern is recommended when either of the following scenarios occur in your application:

  • The object being represented is external to the system.
  • Objects need to be created on demand.
  • Access control for the original object is required
  • Added functionality is required when an object is accessed.

Typically, you’ll want to use a proxy when communication with a third party is an expensive operation, perhaps over a network. The proxy would allow you to hold your data until you are ready to commit, and can limit the amount of times that the communication is called.

The proxy is also useful if you want to decouple actual implementation code from the access to a particular library. Proxy is also useful for access to large files, or graphics. By using a proxy, you can delay loading the resource until you really need the data inside. Without the concept of proxies, an application could be slow, and appear non-responsive.

So How Does It Work In Java?

Let’s continue with the idea of using a proxy for loading images. First, we should create a common interface for the real and proxy implementations to use:

public interface Image
{
  public void displayImage();
}

The RealImage implementation of this interface works as you’d expect:

public class RealImage implements Image
{

   public RealImage(URL url)
   {
      //load up the image
      loadImage(url);
   }

   public void displayImage()
   {
       //display the image
   }

   //a method that only the real image has
  private void loadImage(URL url)
  {
      //do resource intensive operation to load image
  }

}

Now the Proxy implementation can be written, which provides access to the RealImage class. Note that it’s only when we call the displayImage() method that it actually uses the RealImage. Until then, we don’t need the data.

public class ProxyImage implements Image
{
    private URL url; 

    public ProxyImage(URL url)
    {
       this.url = url;
    }

    //this method delegates to the real image
    public void displayImage()
   {
        RealImage real = new RealImage(url);
        real.displayImage();
    }

}

And it’s really as simple as that. As far as the client is concerned, they will just deal with the interface.

Watch Out for the Downsides

Usually this is the stage that I point out the disadvantages to the pattern. Proxy is quite simple, and pragmatic, and it’s one pattern that I can’t think of any downsides for. Perhaps you know of some? If so, please share them in the comments section

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

An Introduction To Cassandra: The Data Model

I’m fairly new to the whole NoSQL game, and one thing I keep hearing is how great Cassandra is. Built by Facebook and open sourced in 2008, Cassandra is probably the most popular NoSQL implementation: “A massively scalable, decentralized, structured data store”. Cassandra takes it’s distribution features from Dynamo and the data model from BigTable.

Before we look at using Cassandra, we first need to understand the data model. For developers new to Cassandra, coming from a relational database background,  the data model can be a bit confusing. Here’s a summary of how the Cassandra data model is composed:

Column

A Column is the most basic element in Cassandra: a simple tuple that contains a name, value and timestamp. All values are set by the client. That’s an important consideration for the timestamp,as it means you’ll need clock synchronization.

SuperColumn

A SuperColumn is a column that stores an associative array of columns. You could think of it as similar to a HashMap in Java, with an identifying column (name) that stores a list of columns inside (value). The key difference between a Column and a SuperColumn is that the value of a Column is a string, where the value of a SuperColumn is a map of Columns. Note that SuperColumns have no timestamp, just a name and a value.

ColumnFamily

A ColumnFamily hold a number of Rows, a sorted map that matches column names to column values.  A row is a set of columns, similar to the table concept from relational databases. The column family holds an ordered list of columns which you can reference by column name.

The ColumnFamily can be of two types, Standard or Super. Standard ColumnFamilys contain a map of normal columns,

meanwhile Super ColumnFamily’s contain rows of SuperColumns.

KeySpaces

KeySpaces are the largest container, with an ordered list of ColumnFamilies, similar to a database in RDMS. The KeySpace is normally named after the application.

Multiple KeySpaces reside in clusters, the machines/nodes in a Cassandra instance.

For another summary of the Cassandra data model, check out the (nicely titled) “WTF is a SuperColumn“.

In the next article in this introduction series, we’ll move onto the good stuff: using Cassandra in Java.

Meanwhile, why not check out Cassandra: The Definitive Guide from Amazon.

If I Could Recommend Eight Books For Java Developers…

There are many books that are essential for your bookshelf if you’re a Java developer. But if I had space for just five books, which ones would I recommend? This question came into my head when I read this post about book recommendations.

Going Back To Basics


Topping the list of essentials for me has to be A Programmer’s Guide to Java Certification. I bought it before I did the certification exam years ago. Even though the edition I have refers to Java 1.4, it’s always been an excellent reference for the basics of the language. Without doubt, it’s the best book available to get going in Java.

Improving Performance


A few years back, I was working on some performance intensive features. I thought I knew threads well enough – I was wrong! This seems to be a common trend among all developers, we don’t have a great grasp on concurrency. Thankfully, Brian Goetz does and published Java Concurrency In Practice

As well as simply explaining threading you’ll find how to design and test your applications for concurrency. As multiple cores become more common this book is a must have for Java developers – especially as we dispel the myth that Java can’t be fast.

Becoming A Better Developer

The Pragmatic Programmer surprised me when I read it first. While not being specific to any language it sets out some great principles, habits and approaches for developers. I still read it every year or so to refresh. It’s been good for my own growth as a developer, and for the growth of development processes I’ve been involved in.

This book should be used in all computer courses, as it would lead to a higher percentage of graduates with a practical view on development.

 

 

I only recently read the highly acclaimed Clean Code by Robert C Martin, and that has proven to another valuable addition to my developer bookshelf. From the very beginnings of the book, you will notice common themes that lead to a poor code base.
If every developer took the time to read this book, I’m sure that software development would have a much better reputation.

Becoming a Java Expert


The second edition of Effective Java has been a welcome addition to my developer bookshelf. It has some great tips that I wouldn’t have picked up had I not read the book. And with such high praise from James Gosling, it’s a book that can’t be ignored.
“I sure wish I had had this book ten years ago. Some might think that I don’t need any Java books, but I need this one.”

The Classics

While this book is outdated in some aspects, if you can afford it, it’s a useful reference to have on your bookshelf. will always be seen as the classic book for software design.

Designing With The Future In Mind


The original GoF Design Patterns book has has set the scene for other books on patterns and design in general. Emergent Design: The Evolutionary Nature of Software Development really caught my attention recently. It has a nice concise appendix of design patterns giving a non-software analog for each, which really helps with understanding them.

It’s a great book for architects and developers to read to make designs more futureproof, stable and helps answer the question How Much Design Is Enough. It easy reading and shows how the software development industry can mature, and what you can do to improve your own practices.

 

Practical Design Patterns


The Head First series really focuses on making it easy to learn the concepts. While the original GoF book can be a bit daunting, I would certainly recommend that software developers, especially novice coders, get this book to see practical implementations of design patterns, written in Java.

 

I’m sure this isn’t the definitive list for all developers so I’d be happy to see your own opinions. What books related to software development have you found indispensable?