Posted by & filed under Uncategorized.

This is second post about Java 8 features in a nutshell. As you remember, last one was about Optional class.

Today I am going to talk about one of the best features of Java 8 which will make your code better and easier to read: Lambda expressions. So what is lambda expression anyway?

If you will sit back and think about evolution of development approach you can remember that first there was code, then there were functions, then there were modules and then OOP. Java is OOP language and everything is an object in Java (yep, yep, apart from primitives). That means that each method you create in java belongs to some class.

Apparently, this introduces some difficulties: for example when you have to create something as simple as Thread doing some task, you have to create Anonymous class which will hold method which you want to execute, which is ok, but creates a lot of boilerplate code.

In that light you can think about lambdas as functions, which are “not bound” to any class or identifier. They make usual tasks simpler and allows express your thoughts in more concise way.

Enough talking, lets look at some code. Lets start with thread example, here what we had to do in Java 7:

Looks familiar, isn’t it? But it has 4 lines of boilerplate code when all you actually wanted to express was “I want to call latch.countDown() in another thread”. Lets see how you can do using lambda expressions in Java 8 :

Looks much better, isn’t it?  I think you already understand what is happening here, but let me explain:

  1. () -> latch.countDown() is lambda expression which creates lambda function which takes no arguments (empty parenthesis) and executes only one line of code
  2. Lambda expressions has access to all the scope variables (include class variables) like Java 7 anonymous functions. Important note: latch is not defined as final here, but it has to be effectively final or declared as final. Behaviour here is same as in methods of anonymous classes, you can’t assign anything else to latch, for example if you put “latch = null;” after thread.start, code would not compile.
  3. There is almosst no boilerplate code.

But what if you want to execute multiple statements? You just need to create a statement block:

But wait, we still have boilerplate piece of code “() ->” which is not required if you are planning to do simple operation of calling one method on latch object. Java 8 allows you to get rid of that boilerplate code as well using method references:

That looks nice, isn’t it? I mean after seeing this, how you can ever code on Java 7, right? :)

Now, lets see how you can use lambda expressions when you need to pass some arguments. We are going to use new Iterable method forEach which appeared in Java 8. I believe code will be self-explanatory:

We are creating list and iterate over it using lambda expression and method reference. All three forEach lines do exactly same thing, and demonstrates how java 8 enables you to write less of boilerplate code.

Now, please take a moment and think about how much clearer your code will be after you replace all your addActionListener(new ActionListener() {….   with one line of method reference getting exactly same functionality. And cherry on top: it is not just syntax sugar, under the hood compiler will actually create more efficient code for you.

I hope now you (better) understand lambda expressions and method references in Java 8. Please use comment form below if you have any questions.

Other posts about Java 8 features:

Posted by & filed under java.

Hope everybody already know that Java 8 is out. It brings a lot of interesting features to make Java easier and more comfortable to use. I will try to talk through some of those features in a nutshell.

Lets start with Optional class. As with all Java 8 features, Optional existed before the release, for example in Guava libraries. Optional class allows you to handle null checks in really nice way. Let’s look at the code. Say we have a User which can have a cat and lets say we have a map of two users Alice and Bob and Alice has a cat:

Now image all you have is a map and you want to get person’s cat name:

You can just lookup key in the map, get User object and get it’s cat and here you go. Unfortunately, couple of calls in this line can return null:

  1. Map.get() can return null
  2. User.getCat() can return null

To overcome that you will have to write two nested if statements as shown on lines 10-16. Quite a lot of code for such simple tasks, right? Imagine if Cat would also have it’s favourite food as well, which can have a brand and you need to get it. Then you will be doomed to add another if and spend end of your life trying to understand how to format in sensible way 4 closing brackets.

Fear not fellow Java developer! Optionals to the rescue! Lets create helper method which will get person’s cat name in NPE-safe way:

Now, let me explain what is happening here:

On line 2 we are wrapping result of map.get() function to Optional object. Optional class is class used to potentially hold some object. It has 3 methods which we touch here indirectly:

  • isPresent() — returns true if Optional is not empty
  • get() — returns object which Optional object holds or throws NoSuchElementException if Optional is empty
  • map() — function which accepts a function which transforms Optional<T> to another Optional<Y>. The magic here is that map will call function only if  original Optional will hold some value, otherwise it will just return empty optional, effectively doing Null check. Try looking at this code how map can work to convert Optional<String> to Optional<T>:

Now, lets get back to getCatName function. Once we got first Optional<User> we apply map function using lambda expression. I will cover them in another blog post, for now you need to understand that it is basically tells to call User::getCat() method BUT on User instance object if Optional<User> is not empty. Line  3 will return Optional<Cat> and we use same trick again to get Cat name, which is returning result as Optional<String>.

Now, we can demonstrate how to use this method:

As you can see, final code is much more clear than original if madness and it deliver same functionality and no NPE.

The “trick” here is that we never return null, we always return Optional object which holds information about previous operation results and allows itself to be used in subsequent operations.

I hope this blog post helped you understand hew Optional class in Java 8. If you have any questions, please use comment form below.

Posted by & filed under devops.

Recently I’ve been playing with Vagrant and I find it to be really useful. I decided even to give it a go on a live server so I can play with different environments safely.

Usually I am using Vagrant on my laptop which is running Mac OS and installing it here is not a big problem. On ubuntu server on the other side, installation is not so straightforward, so I decided to create an ansible playbook to do that.

Perhaps it will be useful to somebody, you can get it on github: vagrant-server-playbook

Let me know if you have any issues with it.

Posted by & filed under grails.

Recently I started to play with Grails 2.3.4 and discovered a lot of nice features around REST, grails team did really good progress here.

When I was playing I noticed that I always had “class” field in JSON returned to me by grails server when I checked the doc, it was saying that you need to setup JSON renderer like this in resources.groovy file:

But when I tried it, it did not work. Well, it did not work for index method, which was returning a collection of devices. You need to define 2 beans: one for collection rendering and another for single object:

Now it will work. Same stands for xml, just use XmlCollectionRenderer instead.

Posted by & filed under cassandra.

We started a tradition of organising a tech talk each month at AirSense. First tech talk was given by me and I talked about cassandra. Check this video and I would be happy to receive any comments and suggestions for improvement. (Yes, chair sounds are terrible :-/ )

Posted by & filed under java.

Introduction

I dont remember how, but occasionally I ended up reading amazing blog of Peter Lawrey about different aspects of Java programming, focused, particularly on performance. Peter also author of Java Chronicle library which he describes as:

This library is an ultra low latency, high throughput, persisted, messaging and event driven in memory database.

Basically, it allows an application to write and read high amount of messages which will be persisted to disc by operating system. Chronicle library supposed to be much faster that simple write to file, since it is using memory mapped files with direct access, which gets persisted to disc by OS.

Since this library looks so cool, I decided to play with it. Unfortunately, there is no tutorials on internet about how to start, so I will share some pieces of code now and then, while I am exploring features of Chronicle

Step 1. Download Chronicle and connect it to your project

You can build chronicle library from source, which you can grub from github. If you are using maven, you can add it as maven dependency:

Step 2. Create a chronicle

There are two basic interfaces in library: Chronicle and Excerpt. Chronicle is “container” for Excerpts. To start using library first thing you need to do is create  Chronicle. There are different types of Chronicles, I will describe them later. In this tutorial we will be using IndexedChronicle:

If you run this code, you will see that library have created two files:

As you can see, files are quite big. That is because library preallocates a lot of data to provide good performance.

Step 3. Create Excerpt in Chronicle

Chronicle is only a “storage” which “holds” excerpts (under the hood it maintains index of each Excerpt in a memory-mapped file). To be able to actually write/read something, you need to create an Excerpt in particular Chronicle:

Excerpt is used both for reading and writing data. But before you can read or write to it, you need to either position it at some index in Chronicle (to read) or, start new excerpt inside linked chronicle with some capacity. Lets go with writing first:

Step 4. Start new excerpt for writing

After you call startExcerpt() you can use writeInt/writeLong/write* methods from RandomDataOutput (defined in com.higherfrequencytrading.chronicle) interface. You need to remember about two points here:

  1. You should know how much data you are going to write, since excerpt has capacity. You can have different capacity for each Excerpt.
  2. You need to call Excerpt.finish(); method for data to be actually saved to Chronicle (and to disc later). This is kind of “commit” for transaction. If you write*() to Excerpt but forgot to call finish(), data will be lost.

Step 5. Read data from Chronicle using Excerpt

Next step is to read data from Chronicle. Each excerpt has some index inside Chronicle. When you are reading from Chronicle, you can sit of Excerpt as Cursor in terms of java collection (although not exactly classic cursor). Reading our test string form Step 4 will look like this:

Step 6. Iterating through all data in Chronicle

Ok, we were able to get one record from Chronicle, but how to we get all records from it? Assuming that all records in Chronicle has one string (as in step 4), you  can iterate over all data like this:

Now I think it is more obvious why you can think of Excerpt as some kind of cursor :)

Step 7. Putting it all together

Ok, time to put all steps together. Here is sample code which opens chronicle in temp directory, writes 3 strings and dumps it. You can run it several times and see that each times you run it, more strings are printed, because data from previous runs is also stored in chronicle.

Summary

Chronicle is a big piece of data where Excerpt are stored. Each Excerpt has index inside Chronicle. Excerpt is a pointer to some memory where you can write data to. Data should be read in the same order it was written, so if you write data to excerpt with two writes: writeLong() and then writeBytes(), it is yours responsibility to read it in the same order (once you positioned your Excerpt in Chronicle). And each Excerpt has a predefined capacity, but you can have different capacity for different Excerpts

I hope this post helped you and now you have basic example of how to read and write data from chronicle and what is looks like. I will continue to play with library and hopefully will write more tutorials. Stay tuned

Posted by & filed under good developer.

It would be “do your job best way you can do it, but expect others to screw up”.

And this advice is not only regarding code, but everything you work with. If there is some chance that something can go wrong, eventually, it will go wrong. If there is possibility of Database getting files corrupted, eventually it will. If there is possibility that some query will take too long and as the result of it, your system will become unresponsive, it will. Your hard drive can fail, compilator can generate incorrect code, data can be not written when OS says it was. On some “perfect friday” it will happen and come from nowhere.

When you are writing software you should always expect different pieces of it to fail. Thinking of possible failure while designing software will make you are better developer. Why? Firstly, because you (hopefully) will create code to deal with potential errors and check returning results of functions calls. Secondly, it will change the way you design your code, so failures in external system have smaller bounders and are easier to recover from. Also, it will clarify your view of interaction points and come up to idea of having general error handling policy, which is always a good thing to have.

As an evolution of this view, you will later realise that you should include yourself in the list of others who can screw up. Yes, all of us makes mistakes :) Accepting that you can make mistake when you are writing new code, or adding new functionality to old code can lead you to unit/integration technics again. These things exists for the only reason that developers are making mistakes.

And you should not forget the first part of the advice. Regardless of expecting others to screw up, you should do your best to do you job well. Thats how you can become good developer, appreciated by others.

By the way, this approach is really useful in life too.  Our life, as software, becomes more and more complex and wether we are able to do something in time or not, depends on a lot of systems and actions of different people. So, expect other to fail and plan enough time to get to airport, especially if you are living in place like London, with its crazy delays which, sometimes, caused by errors in somebody else software, too :).

Posted by & filed under grails.

Recently I encountered really nasty error in grails which took quite some time to fix. It was really hard to find reason because of the really weird stacktrace and it was only happening when being deployed on tomcat server. Exception looked something like this:

First it seem to have something to do with log4j system, but it turns out that HttpBuilder was to blame! It has different version of groovy specified as dependency, which was conflicting with version of groovy coming with grails, causing this nasty error.

To fix it, you need just exclude groovy dependency from HttpBuilder dependency, update your maven section of BuildConfig.groovy like this:

And it should work

Posted by & filed under grails.

One day I needed to lock a record in grails application for update so other transactions does not mess with it while I am updating it. I started digging through the doc and found a section about locking in official documentation. It was pretty straightforward: you just need to use lock() method. So I did this:

And this was working fine. In this basic case. My actual scenario was more complicated, it involved constantly polling database for new messages to process which are not been taken by other workers.

Problem with domain lock() method that if somebody already locked this record, your transaction will wait for that guy to release that lock. In scenario when you are polling database for new messages to process this will definitely mean after some wait you will get message that somebody already start processing.

Solution is simple: we should try to get lock on first record and fail immediately if this is not possible and try to lock next record. And in PostgreSQL you can use syntax SELECT … FOR UPDATE NOWAIT to do this.

A little bit of googling showed me how to do this in grails. It was involving setting lock type directly in Hibernate transaction like this:

But it did not work. Threads were still waiting for other transaction to release message to discover that it is actually being processed by someone. I enabled SQL debug output and saw that query ends with simple FOR UPDATE without NOWAIT.

Long story short: the reason for that that PostgreSQLDialect in PostgreSQL JDBC driver does not support NOWAIT locking. I was using latest driver version: 9.1-901.jdbc4.

Luckily, this problem can be easily solved by extending standard dialect. So, to be able to use FOR UPDATE NOWAIT in PostgreSQL in grails you need to do this:

1. Create your own dialect in src/java folder, or use mine:

2. Update your DataSource.groovy to use this dialect:

And thats it. Now it will work as expected.

Posted by & filed under General.

This post will be not about technical stuff of Android or Grails, but about programming in general.

Yesterday, when I was waiting for my program to start on android I start thinking that I lose quite some time for this start-click-see result cycle. If it takes 30-50 seconds to build upload and start new apk on android, then it can easily end up as half an hour a day just restarting the app.

Then I started to think why I am starting the app so frequently and the reason was simple.

I want to see results of my work.

I want to see how the lines of code I type in eclipse actually doing something, how click on a button works, etc. This is very important thing in any job — to be able to see results of your efforts. When time between this work – result feedback is shorter, and results are easier to understand, then it easier to be more productive.

Now, lets take a look in software development. If you are writing software which is more complicated than Celsius to Fahrenheit converter then you should expect the delay of being seeing results of your work larger. Time for self-feedback increases and you can find yourself writing some code not knowing when it will be actually used. This affect your motivation in bad way and productivity decreases.

When you use test-driven development approach you are creating goals for yourself. First you write test which fails and then make code to pass this test. This is good goal because

  1. It is identifiable
  2. You decide how big goal is
  3. You are getting feedback and ability to see results of your work.

I think the last point is most important, it really takes a lot of effort to keep hight productivity while not being able to see “immediate” results of your work. Having a goal of “releasing product” or building “perfect solution” is great and crucial for actually finishing software, but for everyday work you and members of your team need to see results of their work to see that they are progressing.

Thats why you should consider test-driven development. Thats why it works.