Wednesday, September 7, 2011

JAVA SE 7 has been released, what about JAVA SE 8

Simon Ritter gave a talk about the further development of the JAVA platform at JavaZone 2011 in Oslo. In this blog entry I will try to recap the main aspects of his presentation titled Moving Java Forward: Java SE 7 has been released, what about Java SE 8? and give some additional information where it seems feasible.

Review in the History of Java

JAVA has been started as a project at SUN led by James Gosling back in 1992. The outcome was a compact basis for writing applets which slowly evolved into one of the most widely used programming platforms.

In 1998 the platform made a first major step away from being only a programming and execution environment for applets and swing applications. Back then SUN released version 1.1.2 - named JAVA 2.

Then came 2004 and the announcement of JAVA 5 which finally paved the way into the enterprise platform market. A large set of bitterly missed features were added like generics or annotations.

The next major release (JAVA 6) opened the JVM for scripting languages and provided some management and monitoring features.

On 28th of July 2011 Oracle announced the latest version so far: JAVA 7. It contains features like:

* Parts of Project Coin (strings in switch statements, underscores in binary int literals)
* NIO.2 (I/O improvement towards enhanced platform independence)
* Fork/Join Framework (flexible and reusable synchronization barriers)

Oracle acquired SUN - mission changed?

Since Oracle acquired SUN in January 2010, a lot of rumors and news were spread: positive and negative ones. Unfortunately, this as well as the fact that employees needed to re-position themselves within the new context led to a smaller break in the development of the language. But fortunately Oracle seems to have an open ear to the community and its customers and finally identified four major aspects to follow:

* grow the developer base
* grow the platform adoption
* increase the platform competitiveness
* adapt to change


Beside that, they decided not to have the different stacks (JAVA SE, JAVA EE and JAVA ME) maintained separately but to combine all efforts in one committee in order to reflect that there is just one language.

Although the company committed itself to the adoption of new ideas, this does not imply that they support the incorporation of all suggestions made by users. The overall goal concerning the implementation of language enhancements and new features is code readability. In his talk, Simon Ritter made a nice side blow towards Perl.

Up to now it sounds like if Oracle is trying to get in charge on decisions made whether a feature will be added to the next release or not. But, as Simon Ritter argued in his talk, Oracle will stick to the java community process. However, they will slightly change it to meet the fusion of the three different language stacks: JAVA SE, JAVA EE and JAVA ME. In the end there is one committee which reflects the fact that there is only one language.

Besides work concerning the language itself there is an ongoing process covering the consolidation of the two runtime environments living within the same company: Hotspot and JRockit, where Hotspot is used as source enhanced by JRockit features.

JAVA SE 7 is out, what’s up to JAVA SE 8

So far I have just talked about the history and what happened when Oracle acquired SUN last year. Now I will give some hints on what’s coming next for JAVA 8, which is planned to be released in October 2012.

Maybe I am wrong but from what I have heard and read so far, I would say that JAVA 8 promotes in large parts features that will enhance the multi-core support and bring new language features supporting the programming model required for these types of hardware architectures.

Lambda expressions in parallel collections
A good point to start from is the sorting of collections. Actually it can be done in a serialized way by simply stepping through its contents using a simple for-loop. In JAVA 8 there will be parallel collections having a special filter method the progammer has to provide a predicate to. Filtering will be done with the best hardware utilization as possible. Beside that the collections will have a map function to filter out those attributes the caller is really interested in.

Since JAVA 8 will bring lambda expressions to the platform, these can be used for the filtering purpose as well like:

cars.filter( #{Car c -> c.seats == 2} ).map( #{Car c -> c.age} ).max();
(returns the max. age of all cars having just two seats)

Think about how much code you need to implement this feature using inner classes.

Single Abstract Method Classes
The concept of single abstract method (SAM) classes will make it easier to write inner classes having only one single method. Actually Runnable#run or Comparator#compare are examples of SAMs.

Today we write the following:

car.dummyMethod( new Runnable() { public void run(System.out.println(c.seats));});

Using lambda expressions combined with SAM, we can do the same thing as follows:

car.dummyMethod ( #{Car c -> System.out.println(c.seats)} );

But we will need to follow a set of rules to leverage SAM classes and lambda expressions at their best:

1. Lambda expressions are applicable only in a context where they could be converted into SAM types (eg Runnable, Comparator, Callable, EventHandler):
Object test = #{ 123 } is not allowed
2. Lambda expressions must not have any break or continue statements. Their return type is inferred from the overall set of return statements within the expression.
3. The variable this has the same value as it would have outside the statement.
4. Variables accessed from lambda expressions must not be modified (should be final).

Extension methods
The main idea behind extension methods is the evolvement of APIs without breaking the backwards compatibility. Neal Gafter has written a nice blog entry about this: http://gafter.blogspot.com/2007/11/closures-prototype-update-and-extension.html
At the core of if it, an interface which is extended after it has been made publicly available provides a static standard implementation of the new method(s). All classes implementing the interface and do not provide code for the new method will the standard implementation automatically.

Value classes
Writing DTOs or value classes is one of the most time consuming tasks producing nothing else than classes having some attributes with their associated getter and setter methods. The concept of value classes tries to provide a simple solution where those attributes accessed via getter and setter methods are marked with a special keyword property, ie:

class Node { Node property parent; Node property leftChild; Node propert rightChild; }

Collection literals
Collection literals will solve a common problem when filling lists, sets or maps on creation with pre-defined data. Today this works a follows:

List digits = Collections.unmodifiableList(Arrays.asList([1,2,3]);

The new approach simplifies this:

List digits = [1,2,3];
Map namedDigits = { 1 : “one”, 2 : “two”, 3 : “three” };

module-info.java
I am trying to write a good introduction to this the fourth time right now thus I am just showing the layout of the named file proposed in Simon Ritters talk:

module com.mnxfst.product @ 1.0 {
requires jdom @ 1.0;
requires rome @ 1.0;
class org.openjdk.aggregator.Main;
}

The goal is not just to get rid of the classpath option but also to give the runtime environment sufficient information on how to run the named application correctly. Therefore only those library versions will be used that the developer named in module-info.

Profiles and Modules
The idea behind profiles and modules is to have a single language platform where you choose appropriate components from to support a certain context, eg. enterprise or mobile. In JAVA 8 this is promoted through Project Jigsaw.

Conclusion

Although most of the things I wrote about the upcoming JAVA 8 release are not quite new, I love to see how precise they got by now. Therefore I would like to dedicate the last paragraph to an evaluation of the listed topics:

Oracle acquired Sun
I hope that Oracle will stick to the JAVA community process and keep the platform as free and accessible as possible.

Lambda expressions
Although lambda expressions look a bit different from the java code we currently know, I expect them to improve the language a lot. Not only that they reduce the lines of written code but also make it more readable.

Single Abstract Methods
The same that applies to lambda expressions is also valid for SAMs: they will reduce the written code and make the remaining lines more readable.

Value Classes
In the age of code generators and other neat little helpers, I do not see a real use case for value classes beside the fact that they definitely will reduce the written code. Although I am a bit skeptical, I can say for sure that I will use them if they are available since it spares me to execute the code generator.

Collection Literals
On first sight I was a bit excited about this feature since it makes it really easy to create and fill a collection, list or map on creation. But then they reminded me about the problems I had with the auto (un)boxing feature that moved in with JAVA 5 (int i = list.get(0) might exit with a NPE).
Unfortunately I expect to see the same problems again thus this feature - although really nice and time saving - is not what I was waiting for.

module-info
Since Simon Ritter did not talk too exhaustivly about this feature I am not sure how it will work in practice. Let’s assume an application requires commons-logging 1.0 and a component used by the application requires commons-logging 2.0, how will this work without any troubles? If you’ve got any suggestions or information, please let me know since I am eager to learn about it.
After all I think this is a nice enhancement cleaning up the classpath a bit.

Profiles and Modules
Personally, I have never understood why there are three different type of JAVA specs: SE, EE and ME. Providing a common platform which can be extended concerning its installation footprint according to a specific profile seems to be reasonable. Therefore I must say that I am excited about this.

Saturday, August 27, 2011

Getting Primeface and JSF EL to work on Google App Engine

Lately I decided to use the Google cloud infrastructure as runtime foundation for a new project. At least two reasons led to a positive decision towards Google's App Engine: (1) a very strict but straight development paradigm and (2) the availability of a free quota.

Since I need to get some presentable results quickly and did not want to spend precious time learning a new ui framework, I chose to try out the availability of JSF 2.0 on GAE in interaction with Primefaces. Fortunately I stumbled across an article by Derek Berube on how to setup Primefaces in a GAE environment.

Unfortunately I ran into two small but annoying errors that kept me away from making any progress for a while. The first one appeared everytime I requested a JSF page:

java.lang.UnsupportedOperationException
at javax.faces.context.FacesContext.getCurrentPhaseId(FacesContext.java:660)
at javax.faces.event.ExceptionQueuedEventContext.(ExceptionQueuedEventContext.java:158)
at javax.faces.event.ExceptionQueuedEventContext.(ExceptionQueuedEventContext.java:106)

I could get rid of it by replacing the recommended Mojarra version 2.0.4 by 2.0.3.

The second problem is associated with SUNs implementation of the expression language. So, I replaced it by the JBoss implementation but had to make changes to get it working, since it breaks the law of not spawning any threads. Therefore I copied the modified contents of org.jboss.el.util.ReferenceCache
into the source folder of my project.

Finally I got my project using Primefaces 2.2.1 and JBoss-EL 2.0.1 working.

Thursday, March 10, 2011

Concurrency and Performance (Intro)

In my last blog articles, which are unfortunately more than 4 months old, I wrote about an application I developed during my spare time. Lately I began
to migrate mshop from Spring 3 to JEE 6 for some reasons I may talk about in an upcoming article.

During the refactoring, I came across certain concurrency and performance topics which puzzled me for some time. In parallel a colleague of mine established a company interal workshop series about current software development topics. Since I do think that concurrency and performance are two fundamental topics in software engineering, I offered to prepare a little series about these subjects. As these presentations contain no company secrets, I decided to present them at this place as well. If you have got any ideas or topics you would like to read about, do not hesitate to contact me.

In order to make you aware of the subjects to come, I will present you a typical concurrency situation producing invalid data. Let's assume we have two actors A and B where both share a common bank account BA they try to withdraw money from. To map this into a software I used a very naive approach and modeled a bank account implementation as follows:


/**
* Provides an unsafe bank account implementation
*/
public class UnsafeBankAccount {

private int amount = 0;

/**
* Initializes the account
* @param initialAmount
*/
public UnsafeBankAccount(int initialAmount) {
this.amount = initialAmount;
}

/**
* Withdraws a named amount of money from the account. In
* case the withdrawal is allowed the method returns true
* otherwise false
* @param a
* @return
*/
public boolean withdrawMoney(int a) {

if(a < amount) {
amount = amount - a;
return true;
}

return false;
}

/**
* Returns the current amount of money stored
* in this account
* @return
*/
public int getAmount() {
return amount;
}

}



In a single-threaded environment this implementation would cause no trouble since it is accessed in a sequential manner. If you tend to use the UnsafeBankAccount in a multi-threaded setting, you might observe inconsistent states between the results of UnsafeBankAccount#withdrawMoney and UnsafeBankAccount#getAmount.

Assume the following situation: the actors A and B share a common bank account BA they wish to withdraw money from. At first each checks the current state of the account calling UnsafeBankAccount#getAmount and then decide to withdraw a certain amount of money without overchecking the account. What could happen is:


  • The initial amount of BA is $100

  • A checks the account and sees that the account holds $100

  • A orders to withdraw $30 from the account

  • While the software validates the condition of the if-clause in UnsafeBankAccount#withdrawMoney to true the scheduler interrupts the computation and hands over the control to the thread of B

  • B checks the account as well and also sees that the account holds $100

  • B orders to withdraw $80 from the account

  • The execution thread handling the order of B as well validates the if-clause in UnsafeBankAccount#withdrawMoney to true, recalculates the current state of the account and returns true

  • Now the execution thread handling the order of A also recalculates the current state of the account and returns true as well

  • If any of the customers checks BA, they will see that the account is overchecked by $10



A different situation could be:


  • The initial amount of BA is $100

  • A orders to withdraw $30 from the account

  • Before UnsafeBankAccount#withdrawMoney has the chance to update the variable amount, the scheduler interrupts the current thread

  • Now B checks the current account state by calling UnsafeBankAccount#getAmount and sees that the account still holds $100



To ensure that the bank account works as expected in both cases, we need to ensure that (1) the amount variable is always in a consistent state and (2) each call returning the amount sees the most current value.
The magic element in this case is the synchronized modifier which will be used to guard the reading and writing accesses to amount. This leads to the following modification:


/**
* Provides a thread-safe implementation of a bank account
*/
public class ThreadSafeBankAccount {

private Integer amount = null;

/**
* Initializes the account
* @param intialAmount
*/
public ThreadSafeBankAccount(int intialAmount) {
this.amount = Integer.valueOf(intialAmount);
}

/**
* Withdraws a named amount of money from the account. In
* case the withdrawal is allowed the method returns true
* otherwise false
* @param a
* @return
*/
public boolean withdrawMoney(int a) {

synchronized(amount) {
if(a < amount) {
amount = amount - a;
return true;
}

return false;
}
}

/**
* Returns the current amount of money stored
* in this account
* @return
*/
public int getAmount() {
synchronized(amount) {
return amount;
}
}

}



The implementation above ensures that no read or write access takes place while another thread reads or writes the amount variable. Depending on the use case mapped by the implementation, the synchronisation used in the getter method could be omitted, eg. the caller does not wish to retrieve the latest and most current value.