Sunday, December 25, 2016

Day 25, Java Holiday Calendar 2016, The Complete Deck

Day 25, Java Holiday Calendar 2016, The Complete Deck



Thank you all for following this year's Java Calendar. Here is the complete list with all the articles:



1: Use the @FunctionalInterface Annotation
If you want to ensure API users can use lambdas to implement your interface, it's important to make sure your code is annotated properly. Check out how to do it.

2: Favor Composition Over Inheritance
When you're working with your classes, make sure to use composition when you can for better separation of concerns, among a variety of other reasons. See how it's done.

3: Initializing Maps in the Smartest Way
Learn how you can create and initialize type-safe maps in Java by using two simple utility methods.

4: Use RemoveIf in Java Collections
If you want to remove elements from a collection quick, fast, and in a hurry, take a look at removeIf(), which should save you ton of time over manual iterations.

5: CRUD Operations
See how, with a handy open-source tool, you can alter your database entities, with standard CRUD operations, in Java.

6: Be Lazy With Java 8
If you want your code to kick in only when you need it, then lazy initialization is just right for you. See how you can get it working in Java 8.

7: Access Databases With Streams
Want to query your database with Java? See how Speedment and Java 8's streams can help you get to your data.

8: Use Traits in Java
Using traits can vastly help simplify your code and allow you to reuse components with ease. This example examines using traits with interfaces.

9:Event Sourcing
Event sourcing opens up a new way of looking at your database apps. Turn your database into a record of transactions that you can look back to and restart from.

10: MapStream
The open-source class MapStream lets you stream over elements as well as pairs of key value elements, making changes to everything along the way.

11: Try Java FX
JavaFX offers a variety of features that help improve observability, configure various bindings, and combine with reactive libraries.

12: Avoid Overloading With Lambdas
Lambdas are fantastic, but their popularity might lead to sloppy use. Naming them after specific uses keeps both the compiler and the client happy.

13: Try Higher Order of Functionality
See a QuickSort algorithm in action as an example of Higher Order Functionality. Taking declarative programming to a new level opens new doors to abstraction.

14: Submitting a Task
These days, Java developers have a variety of means to execute tasks. From threads to join pools to caching, you have no shortage of options.

15: Don’t Optimize Now!
If you're going to use JVM, it's important to know what's going on under the hood. Knowing exactly how code flattening works can save you time to put to better use.

16: Hacking the Existing Java Classes
Get your black hat - it's time to hack some classes. But because everyone follows the rules, this tip will help squash third-party bugs and deal with non-standard classes.

17: Parallel Streams in Custom Thread Pools
Java 8's streams, in theory, make it easy to use parallelism. It doesn't always turn out that way, but you can create custom thread pools to expand your resources.

18: Easily Create Database Content
You can use Java and Speedment together to easily analyze your database and generate code and content for it as well.

19: Speed Up Your Enums
The .values() method might seem speedy, but it actually creates a copy of your array, adding to your overhead. Doing a bit of extra work yourself will help in the long run.

20: Break Out of the Java Heap
Moving data off the heap, within reason, can let you work more efficiently while keeping latency low. That way, you can avoid the garbage collection wall for longer.

21: Concatenate Java Streams
Merging your streams through concatenation can allow one stream to lazily consume others, saving you time and making your code more efficient.

22: Use Enums as Method Parameters
Using Enums as parameters can greatly enhance the versatility of your methods. This example shows off how Enums can be used to nimbly and simply sort your lists.

23: Use Mappable Types Instead of Bloated Ones
Using mappable types in your geometric classes means less inter-class coupling and opens up a more functional path -- where you can apply functions on objects.

24: How Many Santas Are There, Really?
Yes, Virginia, there really is a Santa Claus. In fact, there might be a lot of them. Let's do some Java math to see how many Santas it takes to deliver presents around the world.


Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Saturday, December 24, 2016

Day 24, Java Holiday Calendar 2016, How many Santas are there - Really?

Day 24, Java Holiday Calendar 2016, How many Santas are there - Really?



Today we are going to do some nonsense calculations. Is there a Santa and if yes, how many Stantas can we expect to find in the world?

The Assumptions


Let us start with some assumptions. When this article was written there was an estimate of 7,472,085,518 humans on Earth. Let us disregard the guys that lives on the International Space Station, because presumably, Santa's reindeers cannot operate in near-earth-orbit. Luckily for those guys, Elon Musk can deliver their presents via Space X's delivery rocket instead.

A large number of the remaining people are not visited by Santa at all including people of various religious affiliations or beliefs and people that are very poor. We assume that only one third of the remaining persons are visited. We further assume that in average, there are three persons per household (this is not unreasonable taking the vast number of single-person-households into account). Furthermore, we assume that each person gets four presents in average (some rich ones get much more, some poor just get one if they are lucky).

Additionally we estimate that there is an average distance of 500 m (i.e. 0.5 km or 0.3 miles) between each household and that Santa's average sleigh speed is 4 m/s (i.e. 14 km/h or 9 mph) and that it takes Santa 1 second to drop of each present. It should be noted that the actual procedure of handing over presents differs from country to country. In the US, Santa is more likely to drop the packages down the chimney and curve the packages so that they always backspin and land in socks that are hanged near the beginning of the chimney whereas in some European countries, he is more likely to deliver the packages in person. This is note covered in the model though.

Because the speed of the sleigh is not so high, Santa cannot take advantage of the fact that the Earth is rotating and the different time zones. So, Santa can only work 24 hours.

The Java Code 


In Java we can model the problem like this:

public class NumberOfSantas {

    private static final long NUMBER_OF_PERSONS = 7_472_085_518L / 3;
    private static final int PERSONS_PER_HOUSHOLD = 3;
    private static final long NUMBER_OF_HOUSHOLDS = NUMBER_OF_PERSONS / PERSONS_PER_HOUSHOLD;
    private static final int PRESENTS_PER_PERSON = 4;

    private static final int AVERAGE_DISTANCE_BETWEEN_HOUSHOLDS = 500; // m (i.e. 0.5 km or 0.3 miles)
    private static final int AVERAGE_SLEIGH_SPEED = 4; // 4 m/s (i.e. 14 km/h or 9 mph)
    private static final int TIME_TO_DELIVER_PRESENTS = 1; // 1 s 

    private static final int WORKING_HOURS = 24;

    public static void main(String[] args) {

        long totalTimeS = NUMBER_OF_HOUSHOLDS
            * (AVERAGE_DISTANCE_BETWEEN_HOUSHOLDS / AVERAGE_SLEIGH_SPEED)
            + TIME_TO_DELIVER_PRESENTS * NUMBER_OF_PERSONS * PRESENTS_PER_PERSON;

        long noSantas = totalTimeS / (WORKING_HOURS * 3600);

        System.out.format("There are %,d Santas in the world", noSantas);

    }

}

Evidently, there is a large number of Santas out there because the program above outputs the following:

There are 1,316,455 Santas in the world

(Ho, ho)^1.3 M...

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Friday, December 23, 2016

Day 23, Java Holiday Calendar 2016, Use Mappable Types Instead of Bloated Ones

Day 23, Java Holiday Calendar 2016, Use Mappable Types Instead of Bloated Ones



Today's tips is about mappable types. Traditionally we Java developer have relied on inheritance and types with a number of methods to support convenient use of our classes. A traditional Point class would contain x and y coordinates and perhaps also a number of functions that allows us to easily work with our Point.

Imagine now that we add new shapes like Circle and that Circle inherits from Point and adds a radius. Further imagine that there are a bunch of other geometric shapes like Line, Square and the likes that also appear in the code. After a while, all our classes becomes entangled in each other and we end up in a messy hair ball.

However, there is another way of structuring our geometric classes such that there is a minimum of inter-class coupling. Instead of letting each geometric class provide specific methods for translations like add() and flipAroundXAxis() we could add just one or two generic methods that operates on the geometric figure and returns a value of any type. We could then break out the old methods from the geometric classes and convert them to functions and just apply them on the objects rather than letting the objects handle that responsibility.

Let us take the concept for a spin!

Traits

We start with some basic Traits of the geometrical shapes that are shared amongst most shapes. Here are the basic traits:

interface HasX { int x(); } // x is the x-coordinate

interface HasY { int y(); } // y is the y-coordinate

interface HasR { int r(); } // r is the radius

What's the Point?

Now it is time to create our Point interface like this:

interface Point extends HasX, HasY {

    static Point point(int x, int y) {
        return new Point() {
            @Override public int x() { return x; }
            @Override public int y() { return y; }
        };
    }

    static Point origo() { return point(0, 0); }

    default <R> R map(Function<? super Point, ? extends R> mapper) {
        return Objects.requireNonNull(mapper).apply(this);
    }

    default <R, U> R map(BiFunction<? super Point, ? super U, ? extends R> mapper, U other) {
        return Objects.requireNonNull(mapper).apply(this, other);
    }

}

I have purposely refrained from creating an implementation class of the Point interface. Instead, each time the static point() method is called, an instance from an anonymous class is created. This illustrates that the implementation class is "pure" and does not inherit or override anything. In a real solution, there could of course be an implementation of an immutable class PointImpl.

In the middle, there is a conveniency method that return a point in origo (e.g. point(0, 0)).

The two methods at the end of the class are where the interesting stuff starts. They allow us to apply almost any function to a Point.

The first one takes a mapping function that, in turn, takes a point and maps it so something else (i.e. a Function)

The last one takes a mapping function that takes two points and maps it to a Point (e.g. a Binary Function). The mapping function applies the current Point (i.e. "this") as the first parameter and then it also applies another point. That other point is given as the second argument to the map() function. Complicated? Not really. Read more and it will be apparent what is going on.

The Functions

Now we can define a number of useful functions that we could apply to the Point class.

interface PointFunctions {

    static UnaryOperator<Point> NEGATE = (f) -> point(-f.x(), -f.y());
    static BinaryOperator<Point> ADD = (f, s) -> point(f.x() + s.x(), f.y() + s.y());
    static BinaryOperator<Point> SUBTRACT = (f, s) -> point(f.x() - s.x(), f.y() - s.y());
    static UnaryOperator<Point> SWAP_OVER_X_AXIS = (f) -> point(f.x(), -f.y());
    static UnaryOperator<Point> SWAP_OVER_Y_AXIS = (f) -> point(-f.x(), f.y());
    static BinaryOperator<Point> BETWEEN = (f, s) -> point((f.x() + s.x()) / 2, (f.y() + f.y()) / 2);
    static Function<Point, String> TO_STRING = (p) -> String.format("(%d, %d)", p.x(), p.y());
    static BiFunction<Point, Point, Boolean> EQUALS = (f, s) -> (f.x() == s.x()) && (f.y() == s.y());
    //
    static BiFunction<Point, Point, Double> DISTANCE = (f, s) -> Math.sqrt((f.x()-s.x())^2+(f.y()-s.y())^2);
    //
    static Function<Point, UnaryOperator<Point>> ADD2 = s -> (f) -> point(f.x() + s.x(), f.y() + s.y());
}


These methods (or any other similar methods or lambdas) can now be applied to points without polluting the classes.

Example of Usage

This code snippet will create a first point at origo, apply a number of translations to it and then convert it to a string using the TO_STRING mapper. Note how easy it would be to use another string mapper because now the "to string" functionality is separate from the class itself. It would also be easy to use a custom lambda instead of one of the pre-defined functions.

System.out.println(
     origo()
         .map(ADD, point(1, 1))       // 1
         .map(SWAP_OVER_X_AXIS)       // 2
         .map(NEGATE)                 // 3
         .map(BETWEEN, point(-1, -1)) // 4
         .map(TO_STRING)
    );

This will produce the following output:

(-1, 0)

As can be seen in the picture below, this seams to be correct:




Expanding the Concept 

If we later introduce a Circle interface like this

interface Circle extends HasX, HasY, HasR {
  // Stuff similar to Point...
}

and we change our methods so that they can work with the traits directly (and after some additional refactoring not shown here) we can get a decoupled environment where the functions can be made to operate on any relevant shape. For example, the following method can return a "toString" mapper that can work on anything having an x and a y value (e.g. both Point and Circle)

static <T extends HasX & HasY> Function<T, String> toStringXY() {
    return (T t) -> String.format("(%d, %d)", t.x(), t.y());
}

After further modification, we could take a Circle and ADD a Point to it and the circle will be translated using the point's coordinates.

Alternate Solutions

It is possible to wrap any class in an Optional and then use the Optional's map() method to map values. In that case we do not need the map() functions in the shapes. On the other hand, we would have to create an Optional and then also get() the end value once all mappings have been applied.

Another way would be just having a bunch of static methods that takes a Point and other shapes as parameters like this:

static <T extends HasX & HasY> Point add(Point p, T other) {
    return point(p.x() + other.x(), p.y() + other.y());
}

But that... is another story...

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Thursday, December 22, 2016

Day 22, Java Holiday Calendar 2016, Use Enums as Method Parameters

Day 22, Java Holiday Calendar 2016, Use Enums as Method Parameters



Today's tips is about using Enums as parameters to indicate method behavior. Let us here the fairy tail of Prince Sort and it will be more apparent why this can be a good thing.

Once upon a time there was a Prince with a sort method like this:

void sort(); // 1

Everything was good until the Prince realized he needed to sort in either direction. And so, he went about and added a boolean like this:

void sort(boolean descending); // 2

Everything was good until the Prince wanted to indicate that sorting could be done in arbitrary order. And so, he went about and changed the boolean to Boolean:

void sort(Boolean descending); // 3, null means any order

Everything was good until the Prince wanted to indicate that sorting could be done in random order too. And so, he went about and changed the Boolean to an int:

void sort(int flag); // 4, 0 = asc, 1 = desc, 2 = unspec, 3 = random

Now, the most beautiful Princess appeared out of thin air and she wore a wonderful dress and she held the most prominent PhD in computer science. The Princess told the Prince "thou shalt introduce Enums in thy methods". Here is my humble gift to you:

enum Order {
    ASC, DESC, UNSPECIFIED, RANDOM;
}

so, he went about and changed the int to the Order Enum like this:

void sort(Order order);

The Prince was delighted and promised that from now on, he would introduce Enums already in step 2 and they both lived happily ever after!

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Wednesday, December 21, 2016

Day 21, Java Holiday Calendar 2016, Concatenate Java Streams

Day 21, Java Holiday Calendar 2016, Concatenate Java Streams




Today's tip is about concatenating streams. The task of the day is to construct a concatenated stream that lazily consumes a number of underlying streams. So, dumping the content from the various streams into a List and then stream from the list or using the Stream.builder() will not do.

As an example, we have three streams with words that are relevant to the US history and constitution:

        // From 1787
        final Stream preamble = Stream.of(
            "We", "the", "people", "of", "the", "United", "States"
        );

        // From 1789
        final Stream firstAmendment = Stream.of(
            "Congress", "shall", "make", "no", "law", 
            "respecting", "an", "establishment", "of", "religion"
        );

        // From more recent days
        final Stream epilogue = Stream.of(
            "In", "reason", "we", "trust"
        );


Creating a concatenated stream can be done in many ways including these:

        // Works for a small number of streams
        Stream.concat(
            preamble,
            Stream.concat(firstAmendment, epilogue)
        )
            .forEach(System.out::println);

        
        // Works for any number of streams
        Stream.of(preamble, firstAmendment, epilogue)
            .flatMap(Function.identity())
            .forEach(System.out::println);


Both methods will produce the same result and they will also close the underlying streams upon completion. Personally, I prefer the latter method since it is more general and can concatenate any number of streams. This is the output of the program:

We
the
people
of
the
United
States
Congress
shall
make
no
law
respecting
an
establishment
of
religion
In
reason
we
trust

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Tuesday, December 20, 2016

Day 20, Java Holiday Calendar 2016, Breakout of the Java Heap

Day 20, Java Holiday Calendar 2016, Breakout of the Java Heap




Today's tip is about storing things off heap. As we all know, Java will occasionally clean up the heap (i.e. invoke its Garbage Collector or GC for short) and remove objects that are no longer used. As the heap grows, so will the time it takes to clean it up. Eventually, the GC will take seconds or minutes and we have hit "the GC wall". Historically, this was a problem for heaps above some 10 GB of data but nowadays we can have larger heaps. How big depends on a vast number of factors.

One way of reducing GC impact is to store data off heap where the GC is not even looking. This way, we can grow to any data size without caring about the GC. The drawback is that we have to manage our memory manually and also provide a means of converting data back and forth between the two memory regions. In the general case, this is a bit tricky but if we limit ourselves to the primitive types like int, long, double and the likes, it is fairly easy.

Consider the following OffHeapIntArray:

public final class OffHeapIntArray implements Iterable<Integer> {

    private final IntBuffer buffer;
    private final int length;

    public OffHeapIntArray(int length) {
        if (length < 0) {
            throw new IllegalArgumentException();
        }
        this.length = length;
        /* Allocates memory off heap */
        this.buffer = ByteBuffer.allocateDirect(length * Integer.BYTES)
            .asIntBuffer();
    }

    public int get(int index) {
        return buffer.get(index);
    }

    public void set(int index, int value) {
        buffer.put(index, value);
    }

    public int length() {
        return length;
    }

    @Override
    public PrimitiveIterator.OfInt iterator() {
        return new Iter();
    }

    @Override
    public void forEach(Consumer<? super Integer> action) {
        for (int i = 0; i < length; i++) {
            action.accept(i);
        }
    }

    @Override
    public Spliterator.OfInt spliterator() {
        return Spliterators.spliterator(iterator(), length,
            Spliterator.SIZED
            | Spliterator.SUBSIZED
            | Spliterator.NONNULL
            | Spliterator.CONCURRENT
        );
    }

    public IntStream stream() {
        return StreamSupport.intStream(spliterator(), false);
    }

    private final class Iter implements PrimitiveIterator.OfInt {

        private int currentIndex;

        public Iter() {
            currentIndex = 0;
        }

        @Override
        public int nextInt() {
            if (hasNext()) {
                return get(currentIndex++);
            }
            throw new NoSuchElementException();
        }

        @Override
        public void forEachRemaining(IntConsumer action) {
            while (currentIndex < length) {
                action.accept(get(currentIndex++));
            }
        }

        @Override
        public boolean hasNext() {
            return currentIndex < length;
        }

        @Override
        public Integer next() {
            return nextInt();
        }

    }

}

As can be seen, it stores all the int elements off heap and allows us to do a number of things like this:

    public static final void main(String... args) {
        final OffHeapIntArray array = new OffHeapIntArray(10);
        array.set(0, 100);
        array.set(1, 101);
        array.set(9, 109);

        System.out.println("** Iterate **");
        for (int val : array) {
            System.out.println(val);
        }

        System.out.println("** Stream **");
        array.stream()
            .filter(i -> i > 0)
            .forEach(System.out::println);

    }

This will produce the following output:

** Iterate **
100
101
0
0
0
0
0
0
0
109
** Stream **
100
101
109

It is possible to create more advanced off heap classes like OffHeapMap, OffHeapArrayList etc. that store all data off heap in a similar way. Speedment Enterprise is using a more advanced version of this technology to be able to store large databases as in-JVM-memory objects. In fact, it is possible to store more data than the available RAM since byte buffers can be mapped onto files. This opens up the path to mammoth JVMs with terabytes of data available at ultra-low latency.


Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Monday, December 19, 2016

Day 19, Java Holiday Calendar 2016, Speed up Your Enums


Day 19, Java Holiday Calendar 2016, Speed up Your Enums



Today's tips is about Enum performance. A large number of Java programmers think Enums have a very fast method called .values() that returns all the Enums. Heck, it is even an array being returned so it should really be super fast? Well, not really...

Suppose we have declared an enum like this:

public enum Car {

    TESLA, VOLVO, TOYOTA;

}

then it turns out Java will generate an equivalent to the following under the hood:

    public static Car[] values() {
        return (Car[])$VALUES.clone();
    }

This means each time we are calling values(), we are creating a copy of the internal VALUES array. The reason for this is that an array cannot be protected from being overwritten by user code. Thus, a new copy must be provided for each call to guarantee state integrity. The JVM can mitigate the problem under certain circumstances but if we want to be absolutely sure no objects are created, we must implement our own equivalent to values(). This can be done like this:

public enum Car {
    TESLA, VOLVO, TOYOTA;

    private static final List<Car> VALUE_LIST = Stream.of(values())
            .collect(collectingAndThen(toList(), Collections::unmodifiableList));

    public static List<Car> valuesAsList() {
        return VALUE_LIST;
    }

}

Note that the internal VALUE_LIST is unmodifiable and that this is important, or else we cannot expose it directly via the valuesAsList() method.

Now we can use our modified Enum like this with no performance overhead :

Car.valuesAsList().forEach(System.out::println);

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Sunday, December 18, 2016

Day 18, Java Holiday Calendar 2016, Easily Create Database Content


Day 18, Easily Create Database Content




Today's tips is about creating database content. There are a number of ways to do this, ranging from writing our own entity beans combined with using JDBC directly to fully automating the entire process.

Suppose we already have a database table like this:

mysql> explain country
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | NO   | PRI | NULL    | auto_increment |
| name       | varchar(45) | YES  | UNI | NULL    |                |
| local_name | varchar(45) | YES  |     | NULL    |                |
| code       | int(11)     | YES  |     | NULL    |                |
| domain     | varchar(10) | YES  |     | NULL    |                
+------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

Then we could add the Speedment plugin and dependency to our POM and launch the Speedment graphic tool that will analyze the database and generate code automatically for us.

After generation we can do this:

Initialization:

final MyApplication app = new MyApplicationBuilder()
    .withPassword("myPwd729") // Replace with the real pwd
    .build();

final CountryManager countries = app.getOrThrow(CountryManager.class);

Insert DB Content:

countries.persist(
    new CountryImpl()
        .setName("Sweden")
        .setLocalName("Sverige")
        .setCode(40)       // Intentionally wrong, should be 46!!
        .setDomain(".se")
);

Update DB Content:

countries.stream()
    .filter(Country.NAME.equal("Sweden"))  // Filter out Sweden
    .map(c -> c.setCode(46))               // Update code to 46
    .forEach(countries.updater());         // Apply the database updater

Read more on Speedment on GitHub here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Saturday, December 17, 2016

Day 17, Java Holiday Calendar 2016, Parallel Streams in Custom Thread Pools


17. Parallel Streams in Custom Thread Pools



Today's tips is about executing parallel streams in custom thread pools. One of the main drivers for developing the Java 8 streams was their ability to abstract away parallelism. In theory, we could take any stream and make it parallel with the .parallel() method. In reality... not so easy...

One of the caveats with parallel streams is that they, by default, execute on the common Fork Join Pool. So, if there are a lot of things going on in our application, those parallel tasks will compete with all other tasks in the same pool.

This is something that can be fixes easily. A nice thing with all parallel streams is that we can submit the parallel tasks to any Thread Pool, not just the common Thread Pool. In the example below, I am showing how to stream database content in parallel using Speedment, a stream based ORM tool and runtime. This way, complex database operations may execute much faster since the tasks can be spread out on several threads.

However, the same principle would work with any type of stream source such as the ones we get from Java's built-in Collections like List or Set.

Do this:

    final ForkJoinPool forkJoinPool = new ForkJoinPool(3);
    forkJoinPool.submit(() -> 
        
        users.stream() 
            .parallel()
            .filter(User.EMAIL.isNotEmpty())
            .forEach(slowOperation()); 
            
    );

    try {
        forkJoinPool.shutdown();
        forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException ie) {
        ie.printStackTrace();
    } 

This will create a new Fork Join pool with three threads in which the parallel stream will be executed. This way, we limit the number of parallel task to three and they will operate separate from the common Thread Pool. Well, not entirely separate, because tasks in all pools compete for the same limited CPU resources. But that is another story...


Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Friday, December 16, 2016

Day 16, Java Holiday Calendar 2016, Hacking Java Classes

16. Hacking the Existing Java Classes



Today's tips is about hacking the existing Java classes. But before we start, I would like to issue a disclaimer: I am only showing this to illustrate certain possibilities. This post contains code that  is against best-practice and also a number of license terms for commercial JVMs and I would discourage anyone from using this for purposes other than just experimenting in dark cellars at late nights.

The Task

There is a lot of magic going around with auto-boxing and instance caching with wrapper classes like java.lang.Integer. Suppose we could hack the Integer class so it will keep track of how many of its instances are created and how many instances are garbage collected and that we could add a way of retrieving this statistics in some form? How do we go about?

Open Sesame

The JVM has a command line parameter named "-Xbootclasspath/p:" that can be used to load Java classes before the standard java classes are loaded. This way, we can inject our own versions of Java classes before the real ones are loading.

This is useful also for other classes that are not a part of the standard Java library. If there is a bug in a third party product, we can correct the bug and just load the correct version before the app loads. It also enables us to instrument classes so they, for example, can collect usage statistics or introduce or prevent certain things from happening.

Hacking the Integer class

Create a custom class named Integer and place that in a package named java.lang. Retrieve the standard source code of Integer form the JDK and copy that into the custom java.lang.Integer class.

Add the following at the beginning of the copied Integer class:

    public static final AtomicLong INSTANCE_CREATE_COUNTER = new AtomicLong();
    public static final AtomicLong INSTANCE_FINALIZE_COUNTER = new AtomicLong();

Modify the constructor like this:

    public Integer(int value) {
        this.value = value;
        INSTANCE_CREATE_COUNTER.incrementAndGet();
    }

Finally, add the following method:

    @Override
    protected void finalize() throws Throwable {
        INSTANCE_FINALIZE_COUNTER.incrementAndGet();
    }

That's it! We have hacked the Integer class. The modified class can now be used like this:

package org.darkside.hack;

public class Main {

    public static void main(String[] args) {

        printIntegerInstanceInfo();
        Integer i = 456;
        printIntegerInstanceInfo();
        System.gc();
        sleep(1000);
        printIntegerInstanceInfo();

    }

    public static void printIntegerInstanceInfo() {
        long create = Integer.INSTANCE_CREATE_COUNTER.get();
        long finalized = Integer.INSTANCE_FINALIZE_COUNTER.get();
        System.out.format(
            "The JVM has created %d instances and finalized %d instances of Integer."
                + " Thus, %d instances are on the heap.%n",
            create,
            finalized,
            create - finalized
        );
    }

    public static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException ie) {

        }
    }

}

Running the Code

The code can be run like this:

java -Xbootclasspath/p:hack_java_class-1.0.0-SNAPSHOT.jar org.darkside.hack.Main

We have to change the name of the .jar file depending how we named our artifact. Make sure that the modified Integer class and the Main class resides in the same jar. We can also have the modified classes in a separate jar but then we need to add the other parts using the normal class path commands.

Wrap up

The notion here is "Don't Try This at Home". That said, we can learn a lot by injecting custom classes into the JVM.

There are many better ways of keeping track of how many instances that are created and destroyed by the JVM. The task in this post is just for the sake of reasoning.

Be careful out there!





Thursday, December 15, 2016

Day 15, Java Holiday Calendar 2016, Don't Optimize Now!

15. Don't Optimize Now!





Today's tips is about how the JVM can optimize our code. Back in the good ol' Java 1.0 days, I remember running programs that replaced the names of variables, classes and methods so they would become shorter, presumably resulting in faster execution. When things blew up in our faces, we were clueless what really happened because the NPE that method c threw in class D that inherited from class A just didn't provide adequate information as to what really went wrong. It was better before.... not...

These days, the present JVM is just incredible improved over its first incarnations. The JVM will collect statistics on how methods are used and then use that piece of information when it eventually will compile the method with its Just-In-Time (JIT) compiler. This often takes place when a method has been called for about 10 000 times. This is one reason why we should "warm up" our code properly before we run benchmarks.

The JVM is also using a scheme called Code Flattening which means that it is able to "roll up" method calls and consider the code as a larger flow of operations. This way, it is able to determine the possible paths the program can take and consider these paths individually and optimize them. For example, identical range checking that takes place in several methods that call each other can be eliminated. Another example is that dead paths (e.g. where an "if"-branch is using a constant expression) can be eliminated all together.

Another means of optimization is Escape Analysis that is used to determine if an object is visible outside a certain scope. If not, the object can be allocated on the stack rather then on the heap making the program run much faster. Consider the following code snippet:

    @Override 
    public String toString() {
      final StringBuilder sb = new StringBuilder()
        .append("(")
        .append(x)
        .append(", ")
        .append(y)
        .append(")");
      return sb.toString();
  }

Once this code is compiled and when the method has been called a predetermined number of times, the JVM will allocate the StringBuilder on the stack rather than on the heap. Once the method returns, the StringBuilder is cleaned up automatically when the stack is popped upon its return. Because the object cannot be observed from outside, it is also possible to use a simplified representation of the StringBuilder on the stack. So, effectively, the StringBuilder never exists and thus putting in a lot of work to eliminate it is waisted work and will only result in code that looks bad.

One cool thing is that the JVM can combine its optimization schemes. For example, with code flattening, much larger scopes can be used for escape analysis and objects that actually do escape a method might be re-catch on a higher "rolled up" level. Such objects may be subject to stack allocation too. Amazing stuff! 

There are two golden rules when it comes to optimization:

1) Don't optimize
2) Don't optimize now...

That said, when we want to write performance critical applications, it is important to have a basic understanding of the JVM to really know what is going on under the hood. Sometimes it really pays of to rewrite and optimize code.

Speedment, an open-source stream ORM tool and runtime, relies on a number of JVM features to be able to provide efficient execution of its own and application Java code. In particular, the stream implementations benefit substantially from code flattening and escape analysis.

Know your JVM an put your effort where it matters and not in places the JVM will optimize anyhow.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.



Wednesday, December 14, 2016

Day 14, Java Holiday Calendar 2016, Submitting a Task


14. Submitting a Task



Today's tips is about submitting tasks. Historically, we java developers commonly used a new Thread directly when we wanted something to be done in parallel with the current thread. These days, there are a number of other better and more convenient ways of getting the job done.

For the sake of simplicity, we assume that we have a task we want to run that does not return something. This can be modeled using the Runnable interface and we can use lambdas to express our tasks.

Here are a number of alternate ways to execute a task:

public class Main {

    public static void main(String[] args) {
        // Runs in the main thread 
        helloWorld();

        // Runs in a new thread
        new Thread(Main::helloWorld).start();

        // Runs in the default fork join pool
        ForkJoinPool.commonPool().submit(Main::helloWorld);

        // Runs in the default fork join pool via a CompletableFuture
        CompletableFuture.runAsync(Main::helloWorld);

        // Runs in a custom fork join pool (with three workers)
        new ForkJoinPool(3).submit(Main::helloWorld)

        // Queues up task in a single thread executor
        Executors.newSingleThreadExecutor().execute(Main::helloWorld);

        // Caches tasks so that short lived re-occurring tasks can execute faster
        Executors.newCachedThreadPool().execute(Main::helloWorld);

        // Runs in a separate thread pool with the given delay
        Executors.newScheduledThreadPool(2).schedule(Main::helloWorld, 10, TimeUnit.MILLISECONDS);
    }

    public static void helloWorld() {
        System.out.println("Hello World greeting from " + Thread.currentThread().getName());
    }

}

This will produce the following print out:

Hello World greeting from main
Hello World greeting from Thread-0
Hello World greeting from ForkJoinPool.commonPool-worker-1
Hello World greeting from ForkJoinPool.commonPool-worker-1
Hello World greeting from ForkJoinPool-1-worker-1
Hello World greeting from pool-1-thread-1
Hello World greeting from pool-2-thread-1
Hello World greeting from pool-3-thread-1

Remember that in a real case scenario, we need to shut down the custom thread pools we are creating or else our program will not terminate properly (because there are still live threads alive). Closing a thread pool can be made like this:

try {
     forkJoinPool.shutdown();
     forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
 } catch (InterruptedException ie) {
     ie.printStackTrace();
 } 

Read more on thread executing principles on DZone here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.

Tuesday, December 13, 2016

Day 13, Java Holiday Calendar 2016, Try Higher Order of Functionality

13. Higher Order of Functionality



Today's tips is to explore the world of Higher Order Functionality and how to work with functions that operates on functions.

In the good old pre-Java 8 days, algorithms mostly operated on data structures. But with the introduction of  functions in Java 8, our programs may now also reason about behavior. Programming a program that operates on other programs opens up a whole new level of abstractions which allows for elegant declarative programs that express what to be done rather than how, leaving the details about the execution to a framework that performs the operation from "what" to "how" as a higher order operation.

We could, for example, write a QuickSort algorithm that may sort anything (that extends Object) stored anyhow by just providing functional parameters in the form of a getter,  a comparer, a swapper and the number of elements to sort. This enables the QuickSort algorithm to sort lists, arrays or even serialized off heap objects using the same basic algorithm. The QuickSort algorithm just applies the provided functions agnostically. Thus, we only need to write QuickSort once and then we can re-use it by just providing the appropriate functions.

Speedment is an Open Source ORM with an API founded on Java 8 streams. With Speedment you can apply functions that takes functions as a parameter. For example you can:

users.stream()
  .filter(User.BORN.between(1985, 1995)) // Filters out Users born 1985 up to and including 1994
  .map(User.CATEGORY.setTo(3))           // Applies a function that sets their category to 3
  .forEach(users.updater());             // Applies the updater function to the selected users

The code snippet above will;

a) extract users from an underlying database where the users are born between 1985 and 1995 (and only those users)
b) for each such user, it will apply a mapping from a user to an updated user where the category has been set to 3 (but all other fields remain the same)
c) for each updated user, a database updater method will be applied that will result in the updated user being persisted in the database.

So, the snippet above is a sequence of methods that are provided other methods as per the paradigm of Higher Order of Functionality. If we later elect to store our data not in a database but in a file, in memory or even in an Excel diagram, then we only need to provide another set of functions. The stream logic will remain exactly the same.


Read more on Higher Order of Functionality here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Monday, December 12, 2016

Day 12, Java Holiday Calendar 2016, Avoid Overloading with Lambdas

12. Avoid Overloading with Lambdas




Today's tips is to think twice about the names you assign to you methods that can receives lambdas and avoid letting them share the same name.

If there are two or more methods with the same name that take functional interfaces as parameters, then this would likely create a lambda ambiguity on the client side. For example, if there are two Point methods add(Function<Point, String> renderer) and add(Predicate<Point> logCondition) and we try to call point.add(p -> p + “ lambda”) from the client code, the compiler is unable to determine which method to use and will produce an error. Instead, consider naming methods according to their specific use.

I have contributed a lot to the open-source stream based ORM project Speedment and there we have used this naming convention, allowing lambdas to be used in a good way throughout the API.

Do This:

public interface Point {
    addRenderer(Function<Point, String> renderer);
    addLogCondition(Predicate<Point> logCondition);
}


Don't do This:

public interface Point {
    add(Function<Point, String> renderer);
    add(Predicate<Point> logCondition);
}


Read more on Java 8 API design principles on DZone here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Sunday, December 11, 2016

Day 11, Java Holiday Calendar 2016, Try JavaFX

11. Building Reactive Systems with JavaFX




Today's tips is to take the leap from Swing to JavaFX, the latter being much more modern and feature full than the former. 

The open-source Speedment UI tool is built using JavaFX, allowing the tool to be more reactive, in the sense that if we change something in a text box, for example, that property can affect other components directly and dynamically. E.g. if we change the name of a schema, then a tree component showing the entire database structure is updated in real time and perhaps also a connection URL that depends on the schema name. Here is the complete UI tool code written using JavaFX.

Properties and Observability

Property objects are important when designing JavaFX applications. Almost everything in the FX library can be observed such as the text content of a field, the position of a slider or the status of a checkbox. Properties can be Writable and Readable. A writable value can be updated using its setter or by user interaction with the component whereas a readable can react (via notifications) to external events.

Here is how it looks like:

// Both readable and writable
StringProperty name = new SimpleStringProperty("Schema Name"); 

// Only readable
ObservableBooleanValue nameIsEmpty = name.isEmpty();

So, the variable nameIsEmpty can return true if the name is currently empty or false if name is non-empty.

Bindings

Now that we have writable and readable values, we can define custom rules how they all relate to each other (e.g. we can "wire up" our model). Bindings are either unidirectional or bidirectional. Unsurprisingly, bidirectional bindings requires that both properties are writable.

Here is an example of binding:

TextField firstField  = new TextField("first");
TextField secondField = new TextField("second");
firstField.prefWidthProperty().bind(secondField.widthProperty());

This will hint JavaFX that we want our firstTextField to have the same width that the secondField. This relation will be maintained over time so if we change the secondField's width, then the firstField's hinted width is updated automatically.

Tips

JavaFX can be combined with other reactive libraries such as ReactFX and RxJavaFX to create even more powerful applications.

Read more on JavaFX on DZone here and here (Refcardz).

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Saturday, December 10, 2016

Day 10, Java Holiday Calendar 2016, MapStream

Day 10, Java Holiday Calendar 2016, MapStream



Today's tips is about the open-source class MapStream that allows us to stream not only over elements but over pair of key, value elements and make changes either to the keys, values or both.

You can find the source code for MapStream here together with some examples of how to use it. It is free so go ahead and use or copy it in your application! MapStream is a part of open-source Speedment, a stream ORM tool and runtime.

With MapStream you can do this:

Map<String, Integer> numberOfCats = new HashMap<>();

numberOfCats.put("Anne", 3);
numberOfCats.put("Berty", 1);
numberOfCats.put("Cecilia", 1);
numberOfCats.put("Denny", 0);
numberOfCats.put("Erica", 0);
numberOfCats.put("Fiona", 2);

System.out.println(
  MapStream.of(numberOfCats)
      .filterValue(v -> v > 0)
      .sortedByValue(Integer::compareTo)
      .mapKey(k -> k + " has ")
      .mapValue(v -> v + (v == 1 ? " cat." : " cats."))
      .map((k, v) -> k + v)
      .collect(Collectors.joining("\n"))
);

This would produce the following:

Cecilia has 1 cat.
Berty has 1 cat.
Fiona has 2 cats.
Anne has 3 cats.

Learn more on MapStream here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.




Friday, December 9, 2016

Day 9, Java Holiday Calendar 2016, Event Sourcing

9. Event Sourcing



Today's tips is about Event Sourcing which is a relatively new way of designing database applications. Instead of seeing the database as a representation of the most current state, we would see it as a system of record for all transactions that ever took place in our applications. 

So, instead of saying "find person 3 and replace that persons salary with whatever it is right now plus $100" we would say "person 3's salary increased by $100". Note the subtile but important distinction. 

If we use the first scheme, then we would know the current salary but not what it was before, by how much it increased and when it increased. The latter scheme however, allows us to replay all transactions so that we can re-produce all states the application ever had. Great when we are hunting bugs. 

Another important property of event sourcing is that we do not need the (expensive) absolute consistency of the underlying database. Instead, we only need to make sure that the order of the events remain consistent over time.

How do we keep track of the most recent value in an event sourcing system when it is changing all the time? Well, we could implement something called a Materialized View that holds the most current state. So, if we have an event table called employee_events then we could have a Java class EmployeeView that continuously will replay the events in the employees_event table and distiller the fold of all events so that we would actually know what salary person 3 has at the moment.

When the number of events increases, it would be more and more expensive to fast forward all the events, for example when the application restarts. To combat this drawback, the EmployeeView could create periodic snapshots from which it can be restarted. 

Event Sourcing is particularly interesting for applications with a micro service architecture.

Read more about Event Sourcing on Emil Forslund's blog here and on Event Sourcing and Micro Services on eventuate.io here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.




Thursday, December 8, 2016

Day 8, Java Holiday Calendar 2016, Use Traits

8. Use Traits in Java


Today's tips is about defining your classes and interfaces using Traits. This allows you to simplify your code and reuse components efficiently without creating unnecessary coupling or inheritance between your classes.

Suppose we have two district interfaces Table and Column that both have names, then we would introduce a name trait HasName that both interfaces extends. A Table and Column can also have an alias so because of that, we would introduce the trait HasAlias:

    interface Table extends HasName, HasAlias, HasOtherTableProperties {}
    interface Column extends HasName, HasAlias, HasOtherColumnProperties {}
    
    interface HasName {
        void setName(String name);
        String getName();
    }
    
    interface HasAlias {
        void setAlias(String alias);
        String getAlias();
    }
    
    public <T extends HasName & HasAlias> void printNameAndAlias(T item) {
        System.out.format("Name=%2, Alias=%s%n", item.getName(), item.getAlias());
    }

Notice in the last method, printNameAndAlias(), how we define a dynamic compound type T that must be both HasName and HasAlias but does not care about other traits or defined methods. The nice thing now is that once we define a Schema interface like this:

    interface Table extends HasName, HasAlias, HasOtherSchemaProperties {}

Then we can re-use the existing trait methods (e.g. printNameAndAlias()) with no extra effort or coupling. So this would work out-of-the-box:

    Schema schema = ...;
    printNameAndAlias(schema);

The trait scheme is used heavily in the open-source project Speedment that is a stream based ORM tool and runtime. Check out the actual Table and Column code here.

Do this:

    
    interface Table extends HasName, HasAlias, HasOtherTableProperties {}
    interface Column extends HasName, HasAlias, HasOtherColumnProperties {}
    
    interface HasName {
        void setName(String name);
        String getName();
    }
    
    interface HasAlias {
        void setAlias(String name);
        String getAlias();
    }

    public <T extends HasName & HasAlias> void printNameAndAlias(T item) {
        System.out.format("Name=%2, Alias=%s%n", item.getName(), item.getAlias());
    }

Don't do this:

    interface Table {
        void setName(String name);
        String getName();
        void setAlias(String name);
        String getAlias();
        ... other table specific methods
    }
    interface Column {
        void setName(String name);
        String getName();
        void setAlias(String name);
        String getAlias();
        ... other column specific methods
    }

    public void printNameAndAlias(Table item) {
        System.out.format("Name=%2, Alias=%s%n", item.getName(), item.getAlias());
    }

    public void printNameAndAlias(Column item) {
        System.out.format("Name=%2, Alias=%s%n", item.getName(), item.getAlias());
    }

    public void printNameAndAlias(Schema item) {
        System.out.format("Name=%2, Alias=%s%n", item.getName(), item.getAlias());
    }



Read more in the original DZone article at https://dzone.com/articles/using-traits-in-java-8

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Wednesday, December 7, 2016

Day 7, Java Holiday Calendar 2016, Access Databases with Streams

7. Access Databases with Streams


Today's tips is about querying databases using Java 8 streams. By adding both a runtime and plugin dependency to open-source Speedment in you applications Maven POM file, you get access to standard stream implementations of all the database's tables. For MySQL, your POM file could look like this:

<properties>
    <speedment.version="">3.0.1</speedment.version>
    <db.groupid>mysql</db.groupid>
    <db.artifactid>mysql-connector-java</db.artifactid>
    <db.version>5.1.39</db.version>
</properties>

<build>
    <plugins>

        <plugin>
            <groupid>com.speedment</groupid>
            <artifactid>speedment-maven-plugin</artifactid>
            <version>${speedment.version}</version>
            <dependencies>
                <dependency>
                    <groupid>${db.groupId}</groupid>
                    <artifactid>${db.artifactId}</artifactid>
                    <version>${db.version}</version>
                </dependency>
            </dependencies> 
        </plugin>

    </plugins>
</build>
<dependencies>

    <dependency>
        <groupid>com.speedment</groupid>
        <artifactid>runtime</artifactid>
        <version>${speedment.version}</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupid>${db.groupId}</groupid>
        <artifactid>${db.artifactId}</artifactid>
        <version>${db.version}</version>
    </dependency>

</dependencies>

Read more on how to configure your POM file for other database types here which is also the place to be if you want to learn more on Speedment and how to write Speedment applications.

Do this:

users.stream()
    .filter(EMAIL.endsWith(".com"))
    .forEach(System.out::println);

Don't do this:

   Connection conn = null;
   Statement stmt = null;
   try {
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      
      //STEP 4: Execute a query
      stmt = conn.createStatement();

      String sql = "SELECT id, first, last, age, email FROM user";
      ResultSet rs = stmt.executeQuery(sql);
      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve columns
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         String email = rs.getString("email");

         if (email.endsWith(".com")) {
             //Display values
             System.out.print("ID: " + id);
             System.out.print(", Age: " + age);
             System.out.print(", First: " + first);
             System.out.print(", Last: " + last);
             System.out.println(", E-mail: " + email);
         }
      }
      rs.close();
   } catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   } catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   } finally {
      //finally block used to close resources
      try{
         if(stmt!=null)
            conn.close();
      } catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }


Read more in the original DZone article at https://dzone.com/articles/use-smart-streams-with-your-database-in-2-minutes

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Tuesday, December 6, 2016

Day 6, Java Holiday Calendar 2016, Lazy

6. Be Lazy With Java 8




Today's tips is about lazy initialization. Sometimes, we want our classes to do only what is absolutely necessary and nothing more. Immutable classes are particularly good candidates for laziness. Speedment, a Stream ORM Java Toolkit and Runtime, is using Lazy internally and you can find the complete Lazy source code here. Its free so steal it!

By copying this small Lazy class:

public final class Lazy<T> {

    private volatile T value;

    public T getOrCompute(Supplier<T> supplier) {
        final T result = value;  // Read volatile just once...
        return result == null ? maybeCompute(supplier) : result;
    }

    private synchronized T maybeCompute(Supplier<T> supplier) {
        if (value == null) {
            value = requireNonNull(supplier.get());
        }
        return value;
    }

}

You Can Do This:

public class Point {

    private final int x, y;
    private final Lazy<String> lazyToString;

    public Point(int x, int y) {
        this.x = x; 
        this.y = y;
        lazyToString = new Lazy<>();
    }

    @Override
    public String toString() {
        return lazyToString.getOrCompute( () -> "(" + x + ", " + y + ")");
    }

    // The calculation of the toString value is only done once
    // regardless if toString() is called one or several times.
    //
    // If toString() is never called, then the toString value is never
    // calculated.

}

Read more in the original article at http://minborgsjavapot.blogspot.com/2016/01/be-lazy-with-java-8.html

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Monday, December 5, 2016

Day 5, Java Holiday Calendar 2016, CRUD Operations

5. CRUD Operations


Today’s tip is an introduction on how to use open-source Speedment to expand the Java 8 Streams to support Creating, Reading, Updating and Deleting database entities.

Head out to Speedment's GitHub page to see how to modify your project's POM file. Once you done the changes, you can connect to an existing database and generate Java code automatically from the database's meta information (like columns and tables). Once completed, your Java Streams becomes much more feature full and you can:

Do This:

hares.stream()
  .filter(Hare.NAME.equal("Harry"))
  .map(Hare.COLOR.setTo("Brown"))
  .forEach(hares.updater()); 

  // Sets the color to "Brown" for all hares named "Harry" in the DB

Read more on DZone at https://dzone.com/articles/database-crud-operations-in-java-8-streams

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Sunday, December 4, 2016

Creating Maps With Named Lambdas


The Magical Map

Wouldn't it be great if we could create Java maps like this?

Map<String, Integer> map = mapOf(
      one -> 1,
      two -> 2
);

Map<String, String> map2 = mapOf(
      one -> "eins",
      two -> "zwei"
);



Well, we can! Read this post and learn more about lambdas and how we can get the name of their parameters.

The solution

By introducing the following interface we get the functionality above.

public interface KeyValueStringFunction<T> extends Function<String, T>, Serializable {

    default String key() {
        return functionalMethod().getParameters()[0].getName();
    }

    default T value() {
        return apply(key());
    }

    default Method functionalMethod() {
        final SerializedLambda serialzedLabmda = serializedLambda();
        final Class<?> implementationClass = implementationClass(serialzedLabmda);
        return Stream.of(implementationClass.getDeclaredMethods())
            .filter(m -> Objects.equals(m.getName(), serialzedLabmda.getImplMethodName()))
            .findFirst()
            .orElseThrow(RuntimeException::new);
    }

    default Class<?> implementationClass(SerializedLambda serializedLambda) {
        try {
            final String className = serializedLambda.getImplClass().replaceAll("/", ".");
            return Class.forName(className);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    default SerializedLambda serializedLambda() {
        try {
            final Method replaceMethod = getClass().getDeclaredMethod("writeReplace");
            replaceMethod.setAccessible(true);
            return (SerializedLambda) replaceMethod.invoke(this);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SafeVarargs
    static <V> Map<String, V> mapOf(KeyValueStringFunction<V>... mappings) {
        return Stream.of(mappings).collect(toMap(KeyValueStringFunction::key, KeyValueStringFunction::value));
    }

}

Limitations

We can only create maps with keys that are of type String (or anything super String like CharSequence, Serializable or Comparable<String>) because obviously lambda names are strings.

We must use a Java version that is higher than Java 8u80 because it was at that time lambda names could be retrieved run-time.

The most annoying limitation is that we have to compile (i.e. "javac") our code with the "-parameter" flag or else the parameter names will not be included in the run time package (e.g. JAR or WAR). We can do this automatically by modifying our POM file like this:

          <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-Xlint:all</arg>

                        <!-- Add this line to your POM -->
                        <arg>-parameters</arg>
                    </compilerArgs>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>

If you forget to add the "-parameter" flag, the Java runtime will always report a default name of "arg0" as the name of the parameter. This leads to that the maps will (at most) contain one key "arg0", which is not what we want.

Opportunities

The values, can be of any type. In particular they can be other maps, enabling us to construct more advanced map hierarchies. We could, for example, create a map with different countries with values that are also maps containing the largest towns and how many inhabitants each city has like this:


Map<String, Map<String, Integer>> map3 = mapOf(
            usa -> mapOf(
                new_york    -> 8_550_405,
                los_angeles -> 3_971_883,
                chicago     -> 2_720_546
            ),
            canada -> mapOf(
                toronto  -> 2_615_060,
                montreal -> 1_649_519,
                calgary  -> 1_096_833
            )
        );

Update: Important Notes

A number of people have pointed out that SerializedLambda is "thin ice" that we should not rely on in production code. Tagir Valeev (@tagir_valeev) made a performance test of the scheme in this post and compared it to the old fashioned way of just creating a Map and using a regular put() to enter data. The findings were that the old way is orders of magnitudes faster. You can find the entire benchmark here. Thanks Tagir for making this test available. You should view this way of entering data in a Map as academic an as an inspiration of what can be done in Java. Do not use it in production code.

Keep on mapping!

Day 4, Java Holiday Calendar 2016, RemoveIf

4. Use RemoveIf in Java Collections



Today's tips is to use the removeIf() method (that all collection classes like List have) rather than manually iterating over the elements and remove them. For large data sets, removeIf() can be orders of magnitudes faster than other ways. It also looks much better in your code. Why? Read more here and see for your self!

Do This:

items.removeIf(i -> predicate(i));

Don't Do This:

for (Iterator it = items.iterator(); it.hasNext();) {  
    if (predicate(it.next())) {
        it.remove();    
    }
}

Read more in the original article at http://javadeau.lawesson.se/2016/09/java-8-removeif.html

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Saturday, December 3, 2016

Day 3, Java Holiday Calendar 2016, Initialize Maps

3. Initializing Maps in the Smartest Way


Today's tips is how to initialize Java Maps in a type safe way with Java 8. With Java 9, we will get even better ways of creating immutable Maps. Until then, by defining two utility methods:

    public static <K, V> Entry<K, V> entry(K key, V value) {
        return new AbstractMap.SimpleEntry<>(key, value);
    }

    public static <K, U> Collector<Entry<K, U>, ?, Map<K, U>> entriesToMap() {
        return Collectors.toMap(Entry::getKey, Entry::getValue);
    }

You Can Do This:

protected static Map<Integer, String> createMap() {
        return Stream.of(
                entry(0, "zero"),
                entry(1, "one"),
                entry(2, "two"),
                entry(3, "three"),
                entry(4, "four"),
                entry(5, "five"),
                entry(6, "six"),
                entry(7, "seven"),
                entry(8, "eight"),
                entry(9, "nine"),
                entry(10, "ten"),
                entry(11, "eleven"),
                entry(12, "twelve")).
                collect(entriesToMap());
    }

Read more in the original article at http://minborgsjavapot.blogspot.com/2014/12/java-8-initializing-maps-in-smartest-way.html

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.