Java in 2015 – Major happenings

2015 was the year where Java the language, platform, ecosystem and community continue to dominate the software landscape, with only Javascript having a similar sized impact on the industry. In case you missed the highlights of 2015, here’s some of the major happenings that occurred.

Java 20 years old and still not dead yet!

Java turned 20 this year and swept back to the top of the Tiobe index in December 2015. Although the Tiobe index is hardly a 100% peer reviewed scientific methodology, it is seen as a pretty strong barometer for the health of a language/platform. So what the heck happened to boost Java so dramatically again?

Firstly, the release of Java 8 the previous year was adopted by mainstream Java enterprise shops. The additional functional capabilities of Lambdas combined with the new Streams and Collections framework breathed a new lease of life into the language. Although Java 8 is not as rich in its feature set as say Scala or Python it is seen as the steady workhorse that now has at least some feature parity with more aggressive languages. Enterprises love a stable platform and it’s unlikely that Java will be disappearing any time soon.

Secondly, Java has become a strong platform to use for infrastructure platforms/frameworks. Many popular NoSQL, datagrid solutions such as Apache Cassandra, Hazelcast are written in Java, again due to its stability and strong threading and networking support. CI tools such as Jenkins are widely adopted and of course business productivity tools such as Atlassian’s JIRA are again Java based.

Oracle guts its Java evangelism team

Oracle fired much of its Java evangelism team just before JavaOne which wasn’t the greatest PR move by the stewards of Java. Over the subsequent months it became clearer that this wasn’t a step by Oracle to reduce its engineering efforts into Java but there were nervous times for much of the community as they feared the worst. A salient reminder that big corporations don’t always get their left hand talking to their right!

Java 9 delay announced

In the “We’re not really surprised” bucket came the announcement the Java 9 will be delayed until March 2017 in order to ensure that the new modularisation system will not break the millions of Java applications running out there today.

Although the technical work of Jigsaw is progressing nicely, the entire ecosystem will need to test on the new system. The Quality group in OpenJDK is leading this effort. I highly recommend you contact them to be part of the early access and feedback loop.

OpenJDK supports further mobile platforms

The creation of the OpenJDK mobile project came as a surprise to many and although it doesn’t represent a change in Oracle’s business direction it was a wlecome release of code to enable Java on ARM, Android and iOS platforms. There’s much technical work to do but it will be interesting to watch if the software community at large picks up on this new support and tries Java out as a language for the iOS and Android platforms in 2016 and beyond. There is a possibility that OpenFX (JavaFX) combined with Java mobile on iOS or Android may entice a slew of developers to this ‘new’ platform.

Was I right about 2015?

It’s always fun to look at past predictions, let’s see how I did!

  1. I expected 2015 to be a little bit quieter. Well I clearly got that wrong! Despite no major releases for ME, SE or EE, the excitement of celebrating 20 years of Java and a surge of new developers using Java 8 meant 2015 was busier than ever.
  2. Embracing Javascript for the front end. This trend continues and stacks such as JHipster show the new love affair that Java developers have with Javascript.
  3. Devops toolchains to the fore. Docker continues to steamroll ahead in terms of popularity and Java developers are especially starting to use Docker in test environments to avoid polluting environments with variations in Java runtimes, web servers, data stores etc.
  4. IoT and Java to be a thing. Nope, not yet! Perhaps in 2016 with the new Mobile Java project in OpenJDK and further refinement of Java ME, we may start to see serious inroads.

I’m not going to make any predictions for 2016 as I clearly need to stick to my day job ūüôā

One final important note. Project Jigsaw is the modularisation story for Java 9 that will massively impact tool vendors and day to day developers alike. The community at large needs your help to help test out early builds of Java 9 and to help OpenJDK developers and tool vendors ensure that IDEs, build tools and applications are ready for this important change. You can join us in the Adoption Group at OpenJDK. I hope everyone has a great holiday break – I look forward to seeing the Twitter feeds and the GitHub commits flying around in 2016 :-).

Cheers,
Martijn (CEO – jClarity, Java Champion & Diabolical Developer)

This post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on!

Adopt OpenJDK & Java community: how can you help Java !

Introduction

I want to take the opportunity to show what we have been doing in last year and also what we have done so far as members of the community. Unlike other years I have decided to keep this post less technical compare to the past years and compared to the other posts on Java Advent this year.

InTheBeginning

This year marks the fourth year since the first OpenJDK hackday was held in London (supported by LJC and its members) and also when the Adopt OpenJDK program was started. Four years is a small number on the face of 20 years of Java, same goes to the size of the Adopt OpenJDK community which forms a small part of the Java community (9+ million users). Although the post is non-technical in nature, the message herein is fairly important for the future growth and progress of our community and the next generation developers.

Creations of the community

Creations from the community

Over the many months a number of members of our community contributed and passed on their good work to us. In no specific order I have enlisted these picking them from memory. I know there are more to name and you can help us by sharing those with us (we will enlist them here).  So here are some of those that we can talk about and be proud of, and thank those who were involved:

  • Getting Started page – created to enabled two way communication with the members of the community, these include a mailing list, an IRC channel, a weekly newsletter, a twitter handle, among other social media channels and collaboration tools.
  • Adopt OpenJDK project: jitwatch – a great tool created by Chris Newland, its one of its kind, ever growing with features and helping developers fine-tune the performance of your Java/JVM applications running on the JVM.
  • Adopt OpenJDK: GSK – a community effort gathering knowledge and experience from hackday attendees and OpenJDK developers on how to go about with OpenJDK from building it to creating your own version of the JDK. Many JUG members have been involved in the process, and this is now a e-book available in many languages (5 languages + 2 to 3 more languages in progress).
  • Adopt OpenJDK vagrant scripts – a collection of vagrant scripts initially created by John Patrick from the LJC, later improved by the community members by adding more scripts and refactoring existing ones. Theses scripts help build OpenJDK projects in a virtualised container i.e. VirtualBox, making building, and testing OpenJDK and also running and testing Java/JVM applications much easier, reliable and in an isolated environment.
  • Adopt OpenJDK docker scripts – a collection of docker scripts created with the help of the community, this is now also receiving contributions from a number of members like Richard Kolb (SA JUG). Just like the vagrant scripts mentioned above, the docker scripts have similar goals, and need your DevOps foo!
  • Adopt OpenJDK project: mjprof – mjprof is a Monadic jstack analysis tool set. It is a fancy way to say it analyzes jstack output using a series of simple composable building blocks (monads). Many thanks to Haim Yadid for donating it to the community.
  • Adopt OpenJDK project: jcountdown – built by the community that mimics the spirit of ie6countdown.net. That is, to encourage users to move to the latest and greatest Java! Many thanks to all those involved, you can already see from the commit history.
  • Adopt OpenJDK CloudBees Build Farm – thanks to the folks at CloudBees for helping us host our build farm on their CI/CD servers. This one was initially started by Martijn Verburg and later with the help of a number of JUG members have come to the point that major Java projects are built against different versions of the JDK. These projects include building the JDKs themselves (versions 1.7, 1.8, 1.9, Jigsaw and Shenandoah). This project has also helped support the Testing Java Early project and Quality  Outreach program.

These are just a handful of such creations and contributions from the members of the community, some of these projects would certainly need help from you. As a community one more thing we could do well is celebrate our victories and successes, and especially credit those that have been involved whether as individuals or a community. So that our next generation contributors feel inspired and encourage to do more good work and share it with us.

Contributions from the community

We want to contribute

In a recent tweet and posts to various Java / JVM and developer mailing lists, I requested the community to come forward and share their contribution stories or those from others with our community. The purpose was two-fold, one to share it with the community and the other to write this post (which in turn is shared with the community). I was happy to see a handful of messages sent to me and the mailing lists by a number of community members. I’ll share some of these with you (in the order I have received them).

Sebastian Daschner:

I don’t know if that counts as contribution but I’ve hacked on the
OpenJDK compiler for fun several times. For example I added a new
thought up ‘maybe’ keyword which produces randomly executed code:
https://blog.sebastian-daschner.com/entries/maybe_keyword_in_java

Thomas Modeneis:

Thanks for writing, I like your initiative, its really good to show how people are doing and what they have been focusing on. Great idea.
From my part, I can tell about the DevoxxMA last month, I did a talk on the Hacker Space about the Adopt the OpenJDK and it was really great. We had about 30 or more attendees, it was in a open space so everyone that was going to any talk was passing and being grabbed to have a look about the topic, it was really challenging because I had no mic. but I managed to speak out loud and be listen, and I got great feedback after the session. I’m going to work over the weekend to upload the presentation and the recorded video and I will be posting here as soon as I have it done! ūüôā

Martijn Verburg:

Good initiative.  So the major items I participated in were Date and Time and Lambdas Hackdays (reporting several bugs), submitted some warnings cleanups for OpenJDK.  Gave ~10 pages of feedback for jshell and generally tried to encourage people more capable than me to contribute :-).

Andrii Rodionov:

Olena Syrota and Oleg Tsal-Tsalko from Ukraine JUG: Contributing to JSR 367 test code-base (https://github.com/olegts/jsonb-spec), promoting ‚ÄėAdopt a JSR‚Äô and JSON-B spec at JUG UA meetings (http://jug.ua/2015/04/json-binding/) and also at JavaDay Lviv conference (http://www.slideshare.net/olegtsaltsalko9/jsonb-spec).

Contributors

Contributors gathering together

As you have seen that from out of a community of 9+ million users, only a handful of them came forward to share their stories. While I can point you out to another list of contributors who have been paramount with their contributions to the Adopt OpenJDK GitBook, for example, take a look at the list of contributors and also the committers on the git-repo. They have not just contributed to the book but to Java and the OpenJDK community, especially those who have helped translate the book into multiple languages. And then there are a number of them who haven’t come forward to add their names to the list, even though they have made valuable contributions.
Super heroes together

From this I can say contributors can be like unsung heroes, either due their shy or low-profile nature or they just don’t get noticed by us. So it would only be fair to encourage them to come forward or share with the community about their contributions, however simple or small those may be. In addition to the above list I would like to also add a number of them (again apologies if I have missed out your name or not mentioned about you or all your contributions). These names are in no particular order but as they come to my mind as their contributions have been invaluable:

  • Dalibor Topic (OpenJDK Project Lead) & the OpenJDK team
  • Mario Torre & the RedHat OpenJDK team
  • Tori Wieldt (Java Community manager) and her team
  • Heather Vancura & the JCP team
  • NightHacking, vJUG and RebelLabs (and the great people behind them)
  • Nicolaas & the team at Cloudbees
  • Chris Newland (JitWatch developer)
  • Lucy Carey, Ellie & Mark Hazell (Devoxx UK & Voxxed)
  • Richard Kolb (JUG South Africa)
  • Daniel Bryant, Richard Warburton, Ben Evans, and a number of others from LJC
  • Members of SouJava (Otavio, Thomas, Bruno, and others)
  • Members of Bulgarian JUG (Ivan, Martin, Mitri) and neighbours
  • Oti, Ludovic & Patrick Reinhart
  • and a number of other contributors who for some reason I can’t remember…

I have named them for their contributions to the community by helping organise Hackdays during the week and weekends, workshops and hands-on sessions at conferences, giving lightening talks, speaking at conferences, allowing us to host our CI and build farm servers, travelling to different parts of the world holding the Java community flag, writing books, giving Java and advance-level training, giving feedback on new technologies and features, and innumerable other activities that support and push forward the Java / JVM platform.

How you can make a difference ? And why ?

Make a difference

You can make a difference by doing something as simple as clicking the like button (on Twitter, LinkedIn, Facebook, etc…) or responding to a message on a mailing list by expressing your opinion about something you see or read about –as to why you think about it that way or how it could be different.

The answer to the question “And why ?” is simple, because you are part of a community and ‘you care’ and want to share your knowledge and experience with others — just like the others above who have spared free moments of their valuable time for us.

Is it hard to do it ? Where to start ? What needs most attention ?

important-checklist The answer is its not hard to do it, if so many have done it, you can do it as well. Where to start and what can you do ? I have written a page on this topic. And its worth reading it before going any further.

There is a dynamic list of topics that is worth considering when thinking of contributing to OpenJDK and Java. But recently I have filtered this list down to a few topics (in order of precedence):

We need you!

With that I would like to close by saying:

i_need_you_duke3

Not just “I”, but we as a community need you.

This post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on!

Composing Multiple Async Results via an Applicative Builder in Java 8

A few months ago, I put out a publication where I explain in detail an abstraction I came up with named Outcome, which helped me A LOT to code without side-effects by enforcing the use of semantics. By following this simple (and yet powerful) convention, I ended up turning any kind of failure (a.k.a. Exception) into an explicit result from a function, making everything much easier to reason about. I don’t know you but I was tired of dealing with exceptions that teared everything down, so I did something about it, and to be honest, it worked really well. So before I keep going with my tales from the trenches, I really recommend going over that post. Now let’s solve some asynchronous issues by using eccentric applicative ideas, shall we?

Something wicked this way comes

Life was real good, our coding was fast-paced,¬† cleaner and composable as ever, but, out of the blue, we stumble upon a “missing” feature (evil laughs please): we needed to combine several asynchronous Outcome instances in a non-blocking fashion….

ohgodwhy

Excited by the idea, I got down to work. I experimented for a fair amount of time seeking for a robust and yet simple way of expressing these kind of situations; while the new ComposableFuture API turned out to be much nicer that I expected (though I still don’t understand why they decided to use names like applyAsync¬† or thenComposeAsync instead of map or flatMap), I always ended up with implementations too verbose and repetitive comparing to some stuff I did with Scala, but after some long “Mate” sessions, I had my “Hey! moment”: Why not using something similar to an applicative?

The problem

Suppose that we have these two asynchronous results

and a silly entity called Message

I need something that given textf and numberf it will give me back something like

//After combining textf and numberf
CompletableFuture<Outcome<Message>> message = ....

So I wrote a letter to Santa Claus:

  1. I want to asynchronously format the string returned by textf using the number returned by numberf only when both values are available, meaning that both futures completed successfully and none of the outcomes did fail. Of course, we need to be non-blocking.
  2. In case of failures, I want to collect all failures that took place during the execution of textf and/or numberf and return them to the caller, again, without blocking at all.
  3. I don’t want to be constrained by the number of values to be combined,¬† it must be capable of handling a fair amount of asynchronous results. Did I say without blocking? There you go…
  4. Not die during the attempt.

waaat

Applicative  builder to the rescue

If you think about it, one simple way to put what we’re trying to achieve is as follows:

// Given a String -> Given a number -> Format the message
f: String -> Integer -> Message

Checking the definition of¬† f, it is saying something like: “Given a String, I will return a function that takes an Integer as parameter, that when applied, will return an instance of type Message“, this way, instead of waiting for all values to be available at once, we can partially apply one value at a time, getting an actual description of the construction process of a Message instance. That sounded great.

To achieve that, it would be really awesome if we could take the construction lambda Message:new and curry it, boom!, done!, but in Java that’s impossible (to do in a generic, beautiful and concise way), so for the sake of our example, I decided to go with our beloved Builder pattern, which kinda does the job:

And here’s the WannabeApplicative<T> definition

public interface WannabeApplicative<V>
{
    V apply();
}

Disclamer: For those functional freaks out there, this is not an applicative per se, I’m aware of that, but I took some ideas from it an adapted them according to the tools that the language offered me out of the box. So, if you’re feeling curious, go check this post for a more formal example.

If you’re still with me, we could agree that we’ve done nothing too complicated so far, but now we need to express a building step, which, remember, needs to be non-blocking and capable to combine any previous failure that might have took place in other executions with potentially new ones. So, in order to do that, I came up with something as follows:

First of all, we’ve got two functional interfaces: one is Partial<B>, which represents a lazy application of a value to a builder, and the second one, MergingStage<B,V>, represents the “how” to combine both the builder and the value. Then, we’ve got a method called value that, given an instance of type CompletableFuture<Outcome<V>>, it will return an instance of type MergingStage<B,V>, and believe or not, here’s where the magic takes place. If you remember the MergingState definition, you’ll see it’s a BiFunction, where the first parameter is of type Outcome<B> and the second one is of type Outcome<V>. Now, if you follow the types, you can tell that we’ve got two things: the partial state of the building process on one side (type parameter B)¬† and a new value that need to be applied to the current state of the builder (type parameter V), so that, when applied, it will generate a new builder instance with the “next state in the building sequence”, which is represented by Partial<B>. Last but not least, we’ve got the stickedTo method, which basically is a (awful java) hack to stick to a specific applicative type (builder) while defining building step. For instance, having:

I can define partial value applications to any Builder instance as follows:

See that we haven’t built anything yet, we just described what we want to do with each value when the time comes, we might want to perform some validations before using the new value (here’s when Outcome plays an important role) or just use it as it is, it’s really up to us, but the main point is that we haven’t applied anything yet. In order to do so, and to finally tight up all loose ends, I came up with some other definition, which looks as follows:

Hope it’s not that overwhelming, but I’ll try to break it down as clearer as possible. In order to start specifying how you’re going to combine the whole thing together, you will start by calling begin with an instance of type WannabeApplicative<V>, which, in our case, type parameter V is equal to Builder.

FutureCompositions<Message, Builder> ab = begin(Message.applicative())

See that, after you invoke begin, you will get a new instance of FutureCompositions with a lazily evaluated partial state inside of it, making it the one and only owner of the whole building process state, and that was the ultimate goal of everything we’ve done so far, to fully gain control over when and how things will be combined. Next, we must specify the values that we want to combine, and that’s what the binding method is for:

ab.binding(textToApply)
  .binding(numberToApply);

This is how we supply our builder instance with all the values that need to be merged together along with the specification of what’s supposed to happen with each one of them, by using our previously defined Partial instances. Also see that everything’s still lazy evaluated, nothing has happened yet, but still we stacked all “steps” until we finally decide to materialize the result, which will happen when you call perform.

CompletableFuture<Outcome<Message>> message = ab.perform();

From that very moment everything will unfold,¬† each building stage will get evaluated, where failures could¬†be returned and collected within an Outcome instance or simply the newly available values will be supplied to the target builder instance, one way or the other, all steps will be executed until nothing’s to be done. I will try to depict what just happened as follows

applicative

If you pay attention to the left side of the picture, you can easily see how each step gets “defined” as I showed before, following the previous “declaration” arrow direction, meaning, how you actually described the building process. Now, from the moment that you call perform, each applicative instance (remember Builder in our case) will be lazily evaluated in the opposite direction:¬† it will start by evaluating the last specified stage in the stack, which will then proceed to evaluate the next one and so forth up to the point where we reach the “beginning” of the building definition, where it will start to unfold o roll out evaluation each step up to the top, collecting everything¬† it can by using the MergingStage specification.

And this is just the beginning….

I’m sure a lot could be done to improve this idea, for example:

  • The two consecutive calls to dependingOn at CompositionSources.values() sucks, too verbose to my taste, I must do something about it.
  • I’m not quite sure to keep¬†passing¬†Outcome¬†instances to¬†a MergingStage, it would look¬†cleaner¬†and easier¬†if we unwrap the values to be merged before invoking it and just return Either<Failure,V> instead – this will reduce¬†complexity and increase¬†flexibility on what’s supposed to happen behind the scenes.
  • Though using the Builder pattern did the job, it feels old-school, I would love to easily curry constructors, so in my to-do list is to check if jOOőĽ or Javaslang have something to offer on that matter.
  • Better type inference so that the any unnecessary noise gets remove from the code, for example, the stickedTo method, it really is a code smell, something that I hated from the first place. Definitely need more time to figure out an alternative way to infer the applicative type from the definition itself.

You’re more than welcome to send me any suggestions and comments you might have. Cheers and remember…..

index

@gszeliga

Sources

 

A conversational guide for JDK8’s lambdas – a glossary of terms

Last advent…I wrote a post related to the new treats that JDK8 has for us. Most probably the feature that I am the most excited about are the lambdas. I have to admit that in my 1st year of being the prodigal soon (during which I have developed using C#), I loved the LINQ and the nice, elegant things you can do with it. Now, even if erasure is still in the same place where we left it the last time, now we have a better way to filter, alter, walk the collections and beside the syntactic sugar, it might also make you use properly the quad core processor that you bragged about to your friends. And talking about friends this post is a cheatsheet of terms related to lambdas and stream processing that you can throw to your friends when they ask you: “What’s that <place term from JDK 8 related to lambdas>?”. It is not my intent to have a full list or a how-to lambda guide, if I said something wrong or I missed something please let me know…

Functional interface:

According to [jls 8] a functional interface is an interface that has just one abstract method, and thus represents a single function contract (In some cases, this “single” method may take the form of multiple abstract methods with override-equivalent signatures ([jls7_8.4.2]) inherited from superinterfaces; in this case, the inherited methods logically represent a single method).
@FunctionalInterface – is used to indicate that an interface is meant to be a functional interface. If the annotation is placed on an interface that is actually not, a compile time error occurs.
Ex:
interface Runnable { void run(); }
The Runnable interface is a very appropriate example as the only method present is the run method. Another Java “classic” example of functional interface is the Comparator<T> interface, in the following example is a before mentioned interface and the equals method inherited from Object, the interface is still functional as the compare method is the only abstract method, while the equals is inherited from the superclass.

interface Comparator<T> {
  boolean equals(Object obj);

  int compare(T o1, T o2);

}


Stream

stream - according to [oxford dictionary], in computing it is a continuous flow of data or instructions, typically one having a constant or predictable rate.


Starting with JDK 8 stream represents a mechanism used for conveying elements from a data source, through a computational pipeline. A stream can use as data sources arrays, collections, generator functions, I/O channels.


Obtaining streams:

  • From a Collection via the stream() and/or parallelStream() methods;
  • From an array via Arrays.stream(Object[])
  • From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator);
  • The lines of a file can be obtained from BufferedReader.lines();
  • Streams of file paths can be obtained from methods in Files;
  • Streams of random numbers can be obtained from Random.ints();
  • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().

stream operations – actions taken on the stream. From the point of view of stream manipulation there are two types of actions: intermediate and terminal  operations
stream intermediate operation – operations that are narrowing the content of the stream. Intermediate operations are lazy by nature – do not actually alter the content of the stream, but create another narrower stream. The traversal of the stream begins only when the terminal operation is called.
  •  filter – filters the stream based on the provided predicate
  •  map – creates a new stream by applying the mapping function to each element from the initial stream (corresponding methods for each numeric type: int, long, double)
  •  flatMap – operation that has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the results elements into a new stream. For example, if orders is a stream of purchase orders, and each purchase order contains a collection of line items, then the following produces a stream of line items:
                     orderStream.flatMap(order -> order.getLineItems().stream())
  • distinct – returns a stream of distinct operations
  • sorted – returns a stream of sorted operations
  • peek – debug focused method that returns a stream consisting of elements of this stream, the provided action is performed on each element
 Ex:


list.stream()

     .filter(filteringFunction)

     .peek(e -> {System.out.println("Filtered value: " + e); });

     .map(mappingFunction)

     .peek(e -> {System.out.println("Mapped value: " + e); });

     .collect(Collectors.intoList());

  • limit – returns a truncated version of the current stream (no more than the limit number of elements)
  • substream – returns a stream consisting of the remaining element starting from startposition, or between startPosition and endPosition
stream terminal operation – traverse the stream to produce a result or a side-effect. After the execution of the terminal operation, the stream is considered
consumed( calling another operation on a consumed stream will throw an IllegalStateException). Terminal operations are eager in nature, with the exception of iterator() and splititerator() that provide an extension mechanism for those that don’t find the needed function in the API.
  • forEach – applies the provided operation to every element of the stream. Also the forEachOrdered version exists
  • toArray – extracts the elements of the stream into an array
  • reduce  – reduction method
  • collect – mutable reduction method
  • min     – computes the minimum of the stream
  • max     – computes the maximum of the stream
  • count   – counts the elements of the stream
  • anyMatch – returns true if there is an element matching the provided criteria
  • allMatch – returns true if all the elements match
  • noneMatch – returns true if none of the elements match 
  • findFirst – finds the first element that matches the provided condition
  • findAny – returns an element from the stream
stream pipeline: consists of a source, followed by zero or more intermediate operations and a terminal operation.
spliterator – spliterator for traversing and partinioning elements of a source. One can use it for traverse, estimate element count or split it in multiple spliterators
Reduction – a reduction operation (or fold) takes a sequence of input elements and combines them into a single summary result by repeated application
of a combining operation. A reduction operation can be computing the sum, max, min, count or collecting the elements in a list. The reduction operation
is also parallelizable as long as the function(s) used are associative and stateless. The method used for reduction is reduce()
Ex: reduction using sum:
int sum = numbers.stream().reduce(0, (x,y) -> x + y);
or
int sum = numbers.stream().reduce(0, Integer::sum);
Mutable reduction – is a operation that accumulates input elements into a mutable result container (StringBuilder or Collection) as it processes the elements in
the stream.
Ex: String concatenated = strings.reduce("", String::concat)
Predicate – functional interface that determines whether the input object matches some criteria
I hope you find this condensed list beneficial and you keep it in your bookmarks for those moments when you need all these terms on one page.
If you find something that is missing, please let me know so I can correct it.
So…I wish you a nice Advent Time and a Happy/Jolly/Merry but most important of all I wish you a peaceful Christmas!
 Useful resources:
Most of the information was extracted from [stream]. Particularly useful I found the very comprehensive javadoc of the given classes. 
 [jls7_8.4.2] – http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.2

Lambda Related resources on +ManiSarkar‘s recommendation:

https://github.com/AdoptOpenJDK/lambda-tutorial
http://lambdafaq.com

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on!

Java – The 2012 Review and Future Predictions

Hi all,
It’s a real privilege to close off the Java Advent calendar for 2012. It’s a wonderful initiative and I (like many of you) eagerly checked my feed every morning for the next addition. A big Thank You! has to go to +Attila-Mihaly Balazs and all of the other authors for rounding off 2012 in some style.
This post will focus on the events big and small that occurred in 2012 and also take a look at some future predictions for 2013. Some of the predictions will be honest guesses, others…. well lets just say that my Diabolical side will have taken over :-).
So without further adieu lets look at the year that was 2012 for Java…..

2012 – A Year in Review


2012 was a rocking year for Java, the JVM and the community. James Governer (RedMonk analyst) stated that “2012 was the dawning of a 2nd age for Java”.

Java enters the cloud (for real this time)


Java/JVM based cloud offerings became a serious reality in 2012 with a host of new PAAS and IAAS offerings. Cloudbees, JElastic, Heroku, Joyent, Oracle are just five of the large number of offerings out there now.

What does that mean for you as a developer? Well, it means lots of choice and the ability to try out this space very cheaply. I highly recommend that you try some of these providers out over the holidays (it takes minutes to set-up a free account) and see what all of the fuss is about.


Counter to this however is a lack of standardisation in this space and although JEE8 promises to change this (assuming the vendors get on board) – for the next few years you’ll need to be careful about being locked into a particular platform. If you’re a bit more serious about having agnostic services/code running on the various offerings then I can recommend looking at the jClouds API to assist you.

It’s fair to say that many of the offerings are still feeling their way in terms of getting the most out of the JVM. In particular multi-tenancy is an issue, as is Garbage Collection and performance on a virtualised environment.  Companies such as Waratek and jClarity (Disclaimer: I’m their CTO) now offer solutions  to alleviate those gaps.


The Java community thrives


The community continues to thrive despite many main stream tech media reports of “developers leaving the Java platform” or “Java is dead”. There are more Java User Groups (JUGs) than ever before, consisting of ~400,000 developers world wide. Notably, one of them, the London Java Community won several awards including the Duke’s Choice award and JCP Member of the Year (along with SouJava – the major Brazilian JUG).

The conference circuit is bursting at the seams with large, sold out in advance, world-class Java conferences such as JFokus, Devoxx and of course JavaOne. In addition to this the host of regional conferences that often pack in an audience of over 1000 people all continued to do well.

Oracle’s Java Magazine was launched and has grown to over 100,000 subscribers. Stalwarts like JaxEnter, Coderanch and the Javaposse continue to grow in audience sizes.

OpenJDK


Further OpenJDK reforms happened over 2012 and a new scorecard is now in place for the wider community to give feedback on governance, openness and transparency. 2012 also saw a record number of individuals and organisations joining OpenJDK. In particular, the port to the ARM processor and support for running Java on graphic cards (Project Sumatra) were highlights this year.

Java Community Process (JCP)


The Java Community Process (JCP), Java’s standards body also continued its revival with record numbers of new sign-ups and a hotly contested election. As well as dealing with the important business of trademarks, IP and licensing for Java, a re-focus on the technical aspects for Java Specification Requests (JSRs) occurred. In particular the new Adopt a JSR programme is being strongly supported by the JCP.


Java and the JVM


The JVM continues to improve rapidly through OpenJDK – the number of Java Enhancement Proposals (JEPs) going into Java 8 is enormous. Jigsaw dropping out was a disappointing but given the lack of broader vendor support and the vast amount of technical work required, it was the correct decision.

JEE / Spring


JEE7 is moving along nicely (and will be out soon), bringing Java developers a standard way to deal with the modern web (JSON, Web Sockets, etc). Of course many developers are already using the SpringSource suite of APIs but it’s good to see advancement in the underlying specs.

Rapid Web Development


Java/JVM based rapid web development frameworks are finally gaining the recognition they deserve. Frameworks like JBoss’s SEAM, Spring Roo, Grails, Play etc all give Java developers parity with the Rails and Django crowd.

Mechanical Sympathy


A major focus of 2012 was on Mechanical Sympathy (as coined by Martin Thompson in his blog). The tide has turned, and we now have to contend with having multi-core machines and virtualised O/S’s. Java developers have had to start thinking about how Java and the JVM interacts with the underlying platform and hardware.

Performance companies like jClarity are building tooling to help developers understand this complex space, but it certainly doesn’t hurt to get those hardware manuals off the shelf again!

2013 – Future predictions


It’s always fun to gaze into the crystal ball and here are my predictions for 2013!

Java 8 will get delivered on time


Java 8 with Nashorn, Lambda, plus a port to the ARM processor will open up loads of new opportunities for developers working on the leading edge of web and mobile tech. I anticipate rapid adoption of Java 8 (much faster than 7).

However, the lack of JVMs present on iOS and Android devices will continue to curtail adoption there.

Commercial Java in the cloud


2013 will be the year of commercial Java/JVM in the cloud – many of the kinks will get ironed out with regards to mutli-tenancy and memory management and a rich SAAS ecosystem will start to form.


The organisations that enable enterprises to get their in house Java apps out onto the cloud will be the big commercial winners.

We’ll also see some consolidation in this space as the larger vendors snap up smaller ones that have proven technology.

OpenJDK

OpenJDK will continue to truly open up with a public issue tracker based on JIRA, a distributed build farm available to developers and a far superior code review and patch system put in place.

Oracle, IBM and other major vendors have also backed initiatives to bring their in house test suites out into the open, donating them to the project for the good of all. 


JVM languages and polyglot

There will be a resurgence in Groovy thanks to its new static compilation capability and improved IDE tooling. Grails in particular will look like an even more attractive rapid development framework as it will offer decent performance for midrange web apps. 

Scala will continue to be hyped but will only be used successfully by small focused teams.  Clojure will continue to be popular for small niche areas.  Java will still outgrow them all in terms of real numbers and percentage growth.


A random prediction is that JRuby may well entice over Rails developers that are looking to take advantage of the JVM’s performance and scalability.



So that’s it from me, it was an amazing 2012 and I look forward to spending another year working with many of you and watching the rest making dreams into reality!

Cheers,
Martijn (@karianna – CTO of jClarity – aka “The Diabolical Developer”)

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on! Want to write for the blog? We are looking for contributors to fill all 24 slot and would love to have your contribution! Contact Attila Balazs to contribute!

Java – far sight look at JDK 8

The world is changing slowly but surely. After the changes that gave java a fresher look with JDK 7, the java community is looking forward to the rest of the improvements that will come with JDK 8 and probably JDK 9. The targeted purpose of JDK 8 was to fill in the gaps in the implementation of JDK 7 – part of the remaining puzzle pieces laking from this implementation, that should be available for the broad audience by in late 2013 is to improve and boost the language in three particular directions:

  • productivity
  • performance
  • modularity

So from next year, java will run everywhere (mobile, cloud, desktop, server etc.), but in an improved manner. In what follows I will provide a short overview of what to expect from 2013 – just in time for New Year’s Resolutions – afterwards I will focus mainly on productivity side with emphasis on project lambda and how will its introduction affect the way we code.

Productivity

In regards of productivity JDK 8 targets two main areas: – collections – a more facile way to interact with collections through literal extensions brought to the language – annotations – enhanced support for annotations, allowing writting them in contexts where are currently illegal (e.g. primitives)

Performance

The addition of the Fork/Join framework to JDK 7, was the first step that java took in the direction of multicore CPUs. JDK 8 takes this road even further by bringing closures’ support to java (lambda expression, that is). Probably the most affected part of java will be the Collections part, the closures combined with the newly added interfaces and functionalities pushing the java containers to the next level. Besides the more readable and shorter code to be written, by providing to the collections a lambda expression that will be executed internally the platform can take advantage of multicore processors.

Modularity

One of the most interresting pieces for the community was project jigsaw: “The goal of this Project is to design and implement a standard module system for the Java SE Platform, and to apply that system to the Platform itself and to the JDK.”. I am using past tense because, for the those of us that were hoping to get rid of the classpaths and classloaders, we have to postpone our exciment for Java 9, as for that point of time was also project jigsaw postponed.
To have a clearer picture of how the remaning Java Roadmap 2013:

2013/01/31 M6 Feature Complete
2013/02/21 M7 Developer Preview
2013/07/05 M8 Final Release Candidate
2013/09/09 GA General Availability

Besides project jigsaw another big and exciting change that will come (in this version), is the support for closures. Provided through the help of lambda expressions they will improve key points of the JDK.

Lambdas

Getting started

First and first of all one should get a lambda enabled SDK. In this direction there are two ways to obtain one:

 * the one intended for the brave ones: build it from the sources 
 * the convenient one: downloading an already compiled version of the SDK 

 Initially I started with building it from the sources, but due to the lack of time and too many warnings related to environment variables, I opted for the lazy approach and took the already existing JDK. The other important tool is a text editor to write the code. As it happened until now, tipically first came the JDK release and after a period of time, an enabled IDE came out. This time it is different, maybe also due to the transparency and the broad availability of the SDK through openjdk. Some days ago, the first Java 8 enabled IDE was realesed by JetBrain. So IntelliJ IDEA version 12 is the first IDE to provide support for JDK 8, besides are improvements? So for testing purposes I used IntelliJ 12 Community Edition together with JDK 8 b68, on a Windows 7, x64 machine. For those of you that prefer Netbeans, a nightly build with lambda support is available for download.

Adjusting to the appropriate mindset.

Before starting to write improved and cleaner code using the newly provided features, one must get a grasp on a couple new concepts – I needed to, anyway.

  • What is a lambda expression? The easiest way to see a lambda expression is just like a method: “it provides a list of formal parameters and a body‚ÄĒan expression or block‚ÄĒ expressed in terms of those parameters.The parameters of a lambda expression can be either declared or inferred, when the formal parameters have inferred types, then these types are derived from the functional interface type targeted by the lambda expression. From the point of view of the returned value, a lambda expression can be void compatible – they don’t return anything or value compatible – if any given execution path returns a value.
    Examples of lambda expressions:
    (a) (int a, int b) -> a + b

    (b) (int a, int b) -> {
    if (a > b) {
    return a;
    } else if (a == b) {
    return a * b;
    } else {
    return b;
    }
    }

  • What is a functional interface? A functional interface is an interface that contains just one abstract method, hence represents a single method contract. In some situations, the single method may have the form of multiple methods with override-equivalent signatures, in this case all the methods represent a single method. Besides the typical way of creating an interface instance by creating and instantiating a class, functional interface instances can be created also by usage of lambda expressions, method or constructor references.
    Example of functional interfaces:
    // custom built functional interface
    public interface FuncInterface {
    public void invoke(String s1, String s2);
    }

    Example of functional interfaces from the JAVA API:

      java.lang.Comparable
    java.lang.Runnable
    java.util.concurrent.Callable
    java.awt.event.ActionListener

    So let’s see how the starting of a thread might change in the future:
    OLD WAY:

       new Thread(new Runnable() {
    @Override
    public void run() {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }
    }).start();

    NEW WAY:

       new Thread(() -> {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }).start();

    Even if I didn’t write for some time any java Swing, AWT related functionality I have to admit that lambdas will give a breath of fresh air to the Swing developers Action listener addition:

      JButton button = new JButton("Click");

    // NEW WAY:
    button.addActionListener( (e) -> {
    System.out.println("The button was clicked!");
    });

    // OLD WAY:
    button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("The button was clicked using old fashion code!");
    }
    });

  • Who/What is SAM? SAM stands for Single Abstract Method, so to cut some corners we can say that SAM == functional interface. Even if in the initial specification, also abstract classes with only one abstract method were considered SAM types, some people found/guessed also the reason why. 
  • Method/Constructor referencing
  • The lambdas sound all nice and all? But somehow the need for functional interface is somehow to some extend restrictive – does this mean that I can use only interfaces that contain a single abstract method? Not really – JDK 8 provides an aliasing mechanism that allows “extraction” of methods from classes or objects. This can be done by using the newly added :: operator. It can be applied on classes – for extraction of static methods or on objects for extraction of methods. The same operator can be used for constructors also.
    Referencing:

    interface ConstructorReference {
    T constructor();
    }

    interface MethodReference {
    void anotherMethod(String input);
    }

    public class ConstructorClass {
    String value;

    public ConstructorClass() {
    value = "default";
    }

    public static void method(String input) {
    System.out.println(input);
    }

    public void nextMethod(String input) {
    // operations
    }

    public static void main(String... args) {
    // constructor reference
    ConstructorReference reference = ConstructorClass::new;
    ConstructorClass cc = reference.constructor();

    // static method reference
    MethodReference mr = cc::method;

    // object method reference
    MethodReference mr2 = cc::nextMethod;

    System.out.println(cc.value);
    }
    }

  • Default methods in interfaces
  • This means that from version 8, java interfaces can contain method bodies, so to put it simple java will support multiple inheritance without the headaches that usually come with it. Also, by providing default implementations for interface methods one can assure ensure that adding a new method will not create chaos in the implementing classes. JDK 8 added default methods to interfaces like java.util.Collection or java.util.Iterator and through this it provided a mechanism to better use lambdas where it is really needed.
    Notable interfaces added:

       java.util.stream.Streamable
    java.util.stream.Stream

    Improved collections’ interaction In my opinion all the changes that come with project lambda are great additions to the language, that will make it align with the current day standards and make it simpler and leaner but probably the change that will have the biggest productivity impact and the biggest cool + wow effect is definitely the revamping of the collections framework. No, there is no Collection 2 framework, we still have to cope with type erasure for now, but java will make another important shift: from external to internal iteration. By doing so, it provides the developer the mechanism to filter and aggregate collections in an elegant manner and besides this to push for more efficiency. By providing a lambda expression that will be executed internally, so multicore processors can be used to their full power. Let’s consider the following scenarios:
    a. Considering a list of strings, select all of them that are uppercased written. How would this be written? OLD WAY:

      
    //.....

    List inputList = new LinkedList<>();
    List upper = new LinkedList<>();

    // add elements

    for (String currentValue : inputList) {
    if (currentValue != null && currentValue.matches("[A-Z0-9]*")) {
    upper.add(currentValue);
    }
    }

    System.out.println(upper);

    //….. NEW WAY:

      
    //.....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).into(upper);


    b. Consider that you would like to change all the extracted characters to lowercase. Using the JDK8 way this would look like this:

     
    // .....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::toLowerCase).into(upper);


    c. And how about finding out the number of characters from the selected collection

     
    // .....

    int sumX = inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::length).reduce(0, Integer::sum);

    Used methods:

     default Stream stream() // java.util.Collection
    Stream filter(Predicate predicate) // java.util.stream.Stream
    IntStream map(IntFunction mapper) //java.util.stream.Stream


    d. What if I would like to take each element from a collection and print it?

     //OLD WAY:
    for (String current : list) {
    System.out.println(current);
    }

    //NEW WAY:
    list.forEach(x -> System.out.println(x));


    Besides the mentioned functionality, JDK 8 has are other interesting news also, but for brevity reasons I will stop here. More information about it can be found on the JDK 8 Project lambda site or the webpage of the JSR 337.
    To conclude, Java is moving forward and I personally like the direction it is heading, another point of interest would be to point of time when library developers start adopting JDK 8 too. That will be for sure interesting. Thank you for your time and patience, I wish you a merry Christmas.

    Resources

    Brian Goetz resource folder: http://cr.openjdk.java.net/~briangoetz/lambda
    Method/constructor references: http://doanduyhai.wordpress.com/2012/07/14/java-8-lambda-in-details-part-iii-method-and-constructor-referencing

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on! Want to write for the blog? We are looking for contributors to fill all 24 slot and would love to have your contribution! Contact Attila Balazstocontribute!
Disclaimer: This post was based on the JDK8 lambda enabled SDK from 15. December 2012, some features might be subject to change.