Thursday, 14 May 2015

Simple benchmarking : Immutable Collections VS Persistent Collections

Often you need to add new elements to a collection.
Because you are a good and careful developer you want to keep things immutable as much as possible. So adding a new element to an immutable collections will mean that you have to create a new immutable collection that contains all the elements of the original collections plus the new element.

You can create immutable collections using the guava library and also using the recent pCollection library.

In the following example, we will build 2 immutable lists, one immutable from guava and one persistent from pCollection.

They both will contain 10.000 integers initially.

We will create 20.000 immutable lists one for each type and we will measure the time taken.


package com.marco.pcollections;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.pcollections.PCollection;
import org.pcollections.TreePVector;

import com.google.common.collect.ImmutableList;

public class PcollectionVSImmutable {

        public static void main(String[] args) {

                Map<Integer, ImmutableList<Object>> allImmutable = new HashMap<Integer, ImmutableList<Object>>();
                Map<Integer, PCollection<Integer>> allPersistent = new HashMap<Integer, PCollection<Integer>>();

                List<Integer> bigList = new ArrayList<Integer>();
                for (int i = 0; i < 10000; i++) {
                        bigList.add(new Integer(i));
                }

                ImmutableList<Integer> immutable = ImmutableList.copyOf(bigList);

                PCollection<Integer> persistent = TreePVector.from(bigList);

                long start = System.currentTimeMillis();

                for (int i = 10000; i < 30000; i++) {
                        allPersistent.put(new Integer(i), persistent.plus(new Integer(i)));
                }

                System.out.println("creating 20.000 pCollections takes : " + (System.currentTimeMillis() - start) + "ms");

                start = System.currentTimeMillis();

                for (int i = 10000; i < 30000; i++) {
                        allImmutable.put(new Integer(i), ImmutableList.builder().addAll(immutable).add(new Integer(i)).build());
                }

                System.out.println("creating 20.000 Guava ImmutableList takes : " + (System.currentTimeMillis() - start) + "ms");

                System.out.println("All immutable size : " + allImmutable.size() + " allPersistent size : " + allPersistent.size());

        }
}



Output :

creating 20.000 pCollections takes : 29ms
creating 20.000 Guava ImmutableList takes : 18347ms
All immutable size : 20000 allPersistent size : 20000

Monday, 11 May 2015

Immutable Objects with Lombok - workshop

An immutable object is an object whose state cannot be modified after it is created.


Why Immutable Objects are important?


Because you have no total control : objects can be passed anywhere and can arrive from anywhere  in the code. If they are mutable, then any object can modify their state. Different threads can access the same model object and modify/read its state creating many problems difficult to handle.

What is an Immutable object?


Final private fields,  No Setters & Unmodifiable collections

An example ?



What does Lombok?


Project Lombok aims to reduce boilerplate codes by replacing them with a simple set of annotations.

How to install Lombok?


see here : https://projectlombok.org/download.html


Workshop :

Create a model object called Home with the following fields :   

String address;
The street name of your home

int age;
How old were you when you enter this house


int fromYear;
Which year you start living there
int toYear;
Which year you left


Create a toString() method to print the details.




Create a class called MyHomes that prints the list of Homes you lived in.   

This class should create as many homes you lived in and print the details for each one of them. 


Now make the class immutable

Now try to clean the Home class code with Lombok!!

Hints / Immutability support :-

val
@AllArgsConstructor
@Builder
@Value
@FieldDefaults



 
 How can we change a value? 

Add an immutable boolean field to indicate if the address has been verified.

Default should be false.

Add a method to MyHomes to verify a List of Homes


 Now try to use the @Wither annotation from Lombok!!




End of the workshop











Stretch content


































































Saturday, 2 May 2015

In the JVM 1 + 1 = 4

Assuming a and b are equals to 1 :

int a = 1;
int b = 1;

How many JVM operations you see in the following code?

int c = a + b;






The answer is 4 :

iload_0
iload_1
iadd
istore_2


The JVM will load a and b (index 0 and 1 of the local variable array), add them together (in the operand stack), and will assign the result to c (index 2 of the local variable array).


Wednesday, 4 February 2015

Gmail like outlook

We migrated from Outlook to Gmail here at work recently. I love the flat design of Gmail, but I also love the Outlook preview panel on the right when you click on the emails.
So, after a bit of research (and the help of a colleague, thanks Gordon!), I found what I was looking for :



Steps :

  1. On the left panel of your Gmail, where you have the list of your labels,  click on the more link.
  2.  Now click on Manage Labels link.
  3. Here click on the Labs tab.
  4. In the "Search for a lab:" enter  preview pane .
  5. Click on Enable option.
  6. Gmail will reload.
  7. On the top right of the screen there will be a new a drop down menu :
  8. Choose Vertical Split.
  9. Thank me later.

Monday, 2 February 2015

SimpleReact : Simple Functional Reactive Programming for Java 8

We (the very productive and small team I work with here in Aol) have just released a very lightweight functional reactive programming library for Java 8. It builds entirely on pre-existing JDK 8 libraries (so functional interfaces, Streams, CompletableFuture) and makes it very easy to create asynchronous reactive dataflows.

Getting started

Getting started is as simple as setting up a basic Reactive flow such as the following and evolving from there -
 List<String> strings = new SimpleReact()
            .<Integer> react(() -> 1, () -> 2, () -> 3)
            .then(it -> it * 100)
            .then(it -> "*" + it)
            .block();

This will result in a list, that looks something like this :
 ["*100","*200","*300"]

Although not necessarily in that order. All the work will be done asynchronously, and the block() method blocks the current thread until all the work is complete (& blocking the current thread is optional). See more examples on the SimpleReact wiki .

Adding SimpleReact as a dependency


SimpleReact is available on Maven Central.

Gradle


compile group: 'com.aol.simplereact', name:'simple-react', version:'0.1'

Gradle


<dependency>
 <groupId>com.aol.simplereact</groupId>
  <artifactId>simple-react</artifactId>
  <version>0.1</version>
  <scope>compile</scope>
</dependency>
 

Friday, 3 October 2014

Java 8 it's easy : Higher-order Function

higher-order what?

Higher-order means that it is possible to pass to a method both values and functions and in the same way the method itself can return either a value or a function.

Example:
   •    public void doSomething(String name, Function someFunction){...}


   •    public Function createAnAction(Integer someInteger)

EASY!!!!


Use case 1:

Print a message with weight information in kilos. 

This is easy : 

package com.marco.higherOrder;
public class Printer {

        public void print(int weight) {
                System.out.println("Printing : your weight is " + weight + " kilos");
        }

        public static void main(String[] args) {
                Printer printer = new Printer();
                printer.print(65);

        }
}

Use case 2:

I need to be able to print different weight unit like stone and pounds.




Ok, just put an if and shut up!!

Putting an if it means to add and pass a boolean and then check that boolean and put a boring if/else.

Also what about open close principle? what if we need to add yet another weight unit?



Higher-order Function to the rescue:

I want a class in charge of handling different weight units :


package com.marco.higherOrder;
public class Scale {

        public String toStones(int weight) {
                return "your weight is " + weight + " stones";
        }

        public String toKilos(int weight) {
                return "the weight is " + weight + " kilos";
        }

        public String toPounds(int weight) {
                return "the weight is " + weight + " pounds";
        }
}

Then I can add a Function in my Printer.print method and pass functions:


package com.marco.higherOrder;
import java.util.function.Function;
public class Printer {

        public void print(int weight, Function<Integer, String> scale) {
                System.out.println("Printing : " + scale.apply(weight));
        }

        public static void main(String[] args) {
                Printer sender = new Printer();
                Scale scale = new Scale();

                sender.print(65, scale::toKilos);

                sender.print(65, scale::toStones);

                sender.print(65, scale::toPounds);

        }
}

Function<Integer, String> means that this function will accept an Integer and will return a String.

 scale::toKilos means that the method toKilos of the scale instance will be called.
EASY!!!!

What if I don't need the Scale class?

Then don't don't it :)!!!


package com.marco.higherOrder;
import java.util.function.Function;
public class Printer {

        public void print(int weight, Function<Integer, String> scale) {
                System.out.println("Printing : " + scale.apply(weight));
        }

        public static void main(String[] args) {
                Printer sender = new Printer();

                sender.print(65, p -> "your weight is " + p + " kilos");

                sender.print(65, p -> "your weight is " + p + " stones");

                sender.print(65, p -> "your weight is " + p + " pounds");

        }
}
p -> "your weight is " + p + " kilos" the p is simply the int that will be passed to the method.





Functional it’s easy , don’t trust who says it’s hard!


Have a great weekend


Ciao.

Monday, 29 September 2014

Java 8 : Null? no thanks!

You know, I know, they know, everybody knows, returning null from a public method is often a bad practice.
Reasons are multiple, from the risk of raising NullPointerException in runtime to the horrible == null check in your code.

To avoid returning nulls in Java 8 you can use java.util.Optional (if you are on previous version of Java, Guava has similar functionality).

package com.marco;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class NoNullsThanks {

        private final Map<String, Integer> nameAge = new HashMap<String, Integer>();

        public Integer getAge(String name) {
                return Optional.ofNullable(nameAge.get(name)).orElse(-1);
        }

        private final Map<String, List<String>> nameEmails = new HashMap<String, List<String>>();

        public List<String> getEmails(String name) {
                return Optional.ofNullable(nameEmails.get(name)).orElse(new ArrayList<String>());
        }
}


Nice & Clean :)