Javalobby Syndicated Feed

Syndicate content
Recent posts in Java on
Updated: 1 hour 33 min ago

Rust for Java Devs: Creating Variables

4 hours 8 min ago

I’m going to do something different today and write about Rust instead of Java. This is something that I want to give a try, and if it all goes well, I will continue writing some posts about Rust in the future.

I will be writing about learning Rust from the perspective of a Java developer by making comparisons where appropriate to help you (and me) understand what is going on. These will most likely be shorter posts and, honestly, might not even contain that much information — but hopefully, someone finds these sort of posts helpful and makes it all worth it.

Categories: Java

Effective Java 3rd Edition: A Must-Read for Every Developer

8 hours 8 min ago

JosEffective Java 3rd Editionhua Bloch finally updated his popular book Effective Java for Java 7, 8, and 9. The previous edition was one of the most popular books among professional Java developers, and I couldn’t wait to finally read the updated 3rd edition.

I got this book two weeks ago, and it more than fulfilled my expectations. It is packed with best practices and detailed descriptions of the finer details of the Java language. Every developer should at least read the chapters about generics and lambdas.

Categories: Java

Closures in Scala [Video]

14 hours 8 min ago

Before we begin discussing closures in Scala, let us have a quick look at a function. The function literal bill below accepts only one input parameter: netBill. However, the function calculates the final bill by adding a service charge to netBill.

val bill = (netBill: Double) => netBill*(1 + serviceCharge/100)

Categories: Java

An Introduction to Hollow JARs

17 hours 8 min ago

I have written in the past about the difference between an application server and an UberJAR. The short version of that story is that an application server is an environment that hosts multiple Java EE applications side by side, while an UberJAR is a self-contained executable JAR file that launches and hosts a single application.

There is another style of JAR file that sits in-between these two styles called a Hollow JAR.

Categories: Java

Application Design the Java 9 Way

20 hours 8 min ago

Java 8 brought many great improvements to the language. Java 9 enhanced them further! A major paradigm shift now needs to occur. The tools that Java 8 and 9 provide for application design are immensely improved. Java 8 allows static methods on interfaces. Java 9 provides a level of organization above the package: the module. Putting these two techniques together results in better designs and stronger object-oriented guarantees.

Interfaces Rule!

It feels like interfaces passed out of favor in the Java world. There was a time when classes not implementing interfaces were considered suspicious and discussed in code review. Now, major IDEs provide class templates that automatically declare classes public and don't provide or expect an "implements" clause.

Categories: Java

JUnit4, JUnit5, and Spock: A Comparison

Mon, 15-Jan-18 14:01

Recently, I gave a talk in my local Java User Group about unit testing. Some of the content of the talk was about some popular libraries you can use in your Java project. I’ve reviewed JUnit4, JUnit5, and the Spock framework. Many of the attendees were quite surprised with the differences. In this post, I will summarize asserts, parametrized tests, and mocking.

I always like to demonstrate the concepts with examples and live coding, so I chose a simple algorithm: a Fibonacci number calculator. If you don’t know it, it’s just to generate numbers that are the sum of the two previous ones in the series: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377.

Categories: Java

Java Annotated Monthly: January 2018

Mon, 15-Jan-18 10:01

Hopefully, everyone has recovered from the holidays. November is probably one of the craziest months, a sharp contrast to late December and early January, which are some of the quietest ones, at least in my experience. People are wrapping up the year’s results, making plans for the year ahead, and of course, enjoying the holidays. If you had holidays like we did, this January digest might be helpful for updating you on what has happened in the community during the last month. If not, I hope you find the news and articles interesting anyway.

If you missed all the champagne and watched the blogs and social accounts closer than we did, please feel free to share the missing news in the comments. Since Trisha, your regular host, is still on maternity leave; I will do my best to fill in for her.

Categories: Java

Kotlin: Tail Recursion Optimization

Mon, 15-Jan-18 04:01

The Kotlin compiler optimizes tail recursive calls — with a few catches. Consider a ranking function to search for the index of an element in a sorted array, implemented the following way using tail recursion (and a test for it):

fun rank(k: Int, arr: Array<Int>): Int {
    tailrec fun rank(low: Int, high: Int): Int {
        if (low > high) {
            return -1
        val mid = (low + high) / 2
        return when {
            (k < arr[mid]) -> rank(low, mid)
            (k > arr[mid]) -> rank(mid + 1, high)
            else -> mid
    return rank(0, arr.size - 1)
fun rankTest() {
    val array = arrayOf(2, 4, 6, 9, 10, 11, 16, 17, 19, 20, 25)
    assertEquals(-1, rank(100, array))
    assertEquals(0, rank(2, array))
    assertEquals(2, rank(6, array))
    assertEquals(5, rank(11, array))
    assertEquals(10, rank(25, array))

Categories: Java

Spring, Reactor, and ElasticSearch: Benchmarking With Fake Test Data

Mon, 15-Jan-18 01:01

In the previous article, we created a simple adapter from ElasticSearch's API to Reactor's Mono, which looks like this:

import reactor.core.publisher.Mono;

private Mono<IndexResponse> indexDoc(Doc doc) {

Categories: Java

Converting Collections to Maps With JDK 8

Sun, 14-Jan-18 22:01

I have run into situations several times where it is desirable to store multiple objects in a Map instead of a Set or List because there are some advantages from using a Map of unique identifying information to the objects. Java 8 has made this translation easier than ever with streams and the Collectors.toMap(...) methods.

One situation in which it has been useful to use a Map instead of a Set is when working with objects that lack or have sketchy equals(Object) or hashCode() implementations, but do have a field that uniquely identifies the objects. In those cases, if I cannot add or fix the objects' underlying implementations, I can gain better uniqueness guarantees by using a Map of the uniquely identifying field of the class (key) to the class's instantiated object (value). Perhaps a more frequent scenario when I prefer Map to List or Set is when I need to lookup items in the collection by a specific uniquely identifying field. A map lookup on a uniquely identifying key is speedy and often much faster than depending on iteration and comparing each object with an invocation to the equals(Object) method.

Categories: Java

Java 9 Module Services

Sat, 13-Jan-18 23:01

Java has had a ServiceLoader class for a long time. It was introduced in 1.6, but a similar technology was in use from around Java 1.2. Some software components used it, but the use was not widespread. It can be used to modularize an application (even more) and provide a means to extend an application using some kind of plug-ins that the application does not depend on at compile time. Also, the configuration of these services is very simple: Just put it on the class/module path. We will examine the details.

The service loader can locate implementations of some interfaces. In EE environments, there are other methods to configure implementations. In non-EE environments, Spring has become ubiquitous, and it has a similar, though identical, solution to a similar, but not identical, problem.

Categories: Java

Java 9 Modules Introduction (Part 1)

Fri, 12-Jan-18 23:01

In this post, we will introduce the Java Platform Module System (JPMS), which is the biggest change in the Java 9 release. In this post, we will take a look at some basics of the JPMS (Why do we need modules? What has changed in the JDK?). After that, we will take a look at how a single-module application can be created, compiled, and executed. At the end, we will take a look at how a multi-module application can be created, compiled, and executed as well. In this post, we will only use command line tools. The examples used can be found on GitHub.


Let's start with the fundamental question: Why do we need modules anyway? In order to answer that question, we take a look at JSR-376. The following bullets are copied from the JSR:

Categories: Java

Spring Boot With Ehcache 3 and JSR-107

Fri, 12-Jan-18 14:01

Here we are going to cover how to use Ehcache 3 for caching in Spring Boot based on JSR-107. We will tackle how to do operations on the cache itself (besides the well-known annotation usage).

Before we start, let's highlight JSR-107.

Categories: Java

7 Techniques for Thread-Safe Classes

Fri, 12-Jan-18 10:01

Almost every Java application uses threads. A web server like Tomcat process each request in a separate worker thread, fat clients process long-running requests in dedicated worker threads, and even batch processes use the java.util.concurrent.ForkJoinPool to improve performance.

It is, therefore, necessary to write classes in a thread-safe way, which can be achieved by one of the following techniques.

Categories: Java

The Highly Useful Java ChronoUnit Enum

Fri, 12-Jan-18 04:01

Several years ago, I published the blog post "The Highly Useful Java TimeUnit Enum" that looked at the TimeUnit enum introduced with JDK 5. JDK 8 introduced a newer enum, ChronoUnit, that is better suited than TimeUnit for contexts other than concurrency such as date/time manipulations.

Located in the java.time.temporal package, the ChronoUnit class implements the TemporalUnit interface, an interface used extensively in the highly desired JDK 8-introduced Date/Time API. The blog post "Days Between Dates in Java 8" demonstrates use of this class to calculate periods of time between two instances of Temporal.

Categories: Java

Jackson Mix-In Annotations

Fri, 12-Jan-18 01:01

Prior to Jackson 1.2, the only way to serialize or deserialize JSON using Jackson was by using one of the following two methods:

  • Adding annotations to modify the POJO classes
  • Writing custom serializers and deserializers

Now imagine you want to serialize or deserialize a third-party POJO which you don’t have access to its source code. What would you do?

Categories: Java

Bootiful Development With Spring Boot and React

Thu, 11-Jan-18 22:01

React has been getting a lot of positive press in the last couple years, making it an appealing frontend option for Java developers! Once you learn how it works, it makes a lot of sense and can be fun to develop with. Not only that, but it’s wicked fast! If you’ve been following me, or if you’ve read this blog for a bit, you might remember my Bootiful Development with Spring Boot and Angular tutorial. Today, I’ll show you how to build the same application, except with React this time. Before we dive into that, let’s talk some more about what React is great for, and why I chose to explore it in this post.

First of all, React isn’t a full-fledged web framework. It’s more of a toolkit for developing UIs, a la GWT. If you want to make an HTTP request to fetch data from a server, React doesn’t provide any utilities for that. However, it does have a huge ecosystem that offers many libraries and components. What do I mean by huge? Put it this way: According to npmjs.comAngular has 17,938 packages. React has almost three times as many at 42,428!

Categories: Java

Spring Boot Classloader and Class Overriding

Thu, 11-Jan-18 10:01

This article explains the Spring Boot classloader (LaunchedURLClassLoader) and a way to temporarily override library classes with your custom ones. 

Just a Little Fix

Let’s say you found a bug in some third-party JAR your app uses. As a good scout, you fixed it and created a pull request with a solution. The pull request was merged, but the fix is critical for you and you can’t wait till next library release. Is using a library snapshot the only way? Wouldn’t it be great if there was a solution to temporarily override only a few particular classes?

Categories: Java

The Builder Design Pattern for Big Classes

Thu, 11-Jan-18 04:01

As per the original definition of Builder Design Pattern, it separates the construction of a complex object from its representation so that the same construction process can create different representations. One side effect of this pattern is that we can avoid mistakes associated with the construction of an object with a constructor that takes too many arguments. For example, consider the following class:

public class Employee {
      private int id;
      private String name;
      private String department;
      private String address;
      private String phone;
      private String mobile;

      public Employee(String name, String deptt, String address,
                  String phone, String mobile) {
   = generateId();
   = name;
            this.deptt = deptt;
            this.address = address;
   = phone;
   = mobile;

      private int generateId(){
            int id = 0; //Generate a unique id here with some mechanism
            return id;

Categories: Java

Spring, Reactor, and ElasticSearch: From Callbacks to Reactive Streams

Thu, 11-Jan-18 01:01

Spring 5 (and Boot 2, when it arrives in a couple of weeks) is a revolution. Not the "annotations over XML" or "Java classes over annotations" type of revolution. It's truly a revolutionary framework that enables writing a brand new class of applications.

In recent years, I became a little bit intimidated by this framework. Spring Cloud is a framework that simplifies the usage of Spring Boot, which is a framework that simplifies the usage of Spring, which is a framework that simplifies enterprise development.

Categories: Java

Thread Slivers eBook at Amazon