Minborg

Minborg
Minborg

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.