Default interface functions in Java 8

Introduction

A new feature in Java 8 is default function implementations. They are default implementations of methods of an interface. Default methods can help extending an interface without breaking the existing implementations. After all if you add a new method to an interface then all implementing types must handle it otherwise the compiler will complain.

This can be cumbersome if your interface has a large number of consumers. You’ll break their code and they will need to implement the new function – which they might not even need.

Read more of this post

Waiting for background tasks to finish using the CompletableFuture class in Java

Introduction

In this post we saw how to wait for a number background tasks to finish using the CountDownLatch class. The starting point for the discussion was the following situation:

Imagine that you execute a number of long running methods. Also, let’s say that the very last time consuming process depends on the previous processes, let’s call them prerequisites. The dependence is “sequential” meaning that the final stage should only run if the prerequisites have all completed and returned. The first implementation may very well be sequential where the long running methods are called one after the other and each of them blocks the main thread.

However, in case the prerequisites can be executed independently then there’s a much better solution: we can execute them in parallel instead. Independence in this case means that prerequisite A doesn’t need any return value from prerequisite B in which case parallel execution of A and B is not an option.

In this post we’ll look at an alternative solution using the CompletableFuture class. It is way more versatile than CountDownLatch which is really only sort of like a simple lock object. CompletableFuture offers a wide range of possibilities to organise your threads with a fluent API. Here we’ll start off easy with a simple application of this class.

Read more of this post

Sharing primitives across threads in Java using atomic objects

Threading and parallel execution are popular choices when making applications more responsive and resource-efficient. Various tasks are carried out on separate threads where they either produce some result relevant to the main thread or just run in the background “unnoticed”. Often these tasks work autonomously meaning they have their own set of dependencies and variables. That is they do not interfere with a resource that is common to 2 or more threads.

However, that’s not always the case. Imagine that multiple threads are trying to update the same primitive like an integer counter. They perform some action and then update this counter. In this post we’ll see what can go wrong.

Read more of this post

Check available number of bytes in an input stream in Java

In this post we saw how to read the bytes contained in an input stream. The most common way to achieve it is by way of one of the read methods. The overloaded version where we provide a target byte array, an offset and a total byte count to be read is probably used most often.

It can happen in real-life situations that we provide the total number of bytes to be extracted but those bytes have not yet “arrived”, i.e. are not yet available in the input stream. This can occur when reading the bytes from a slow network connection. The bytes will eventually be available. The read method will block the thread it’s running in while it is waiting for the bytes to be loaded.

Read more of this post

Reading text files using the Stream API in Java 8

We discussed the Java 8 Stream API thoroughly on this blog starting here. We mostly looked at how the API is applied to MapReduce operations to analyse data in a stream.

The same API can be applied to File I/O. Java 8 adds a new method called “lines” to the BufferedReader object which opens a Stream of String. From then on it’s just standard Stream API usage to filter the lines in the file – and perform other operations on them in parallel such as filtering out the lines that you don’t need.

Here’s an example how you can read all lines in a file:

Read more of this post

Localising dates in Java using DateTimeFormatter

Introduction

In this post we saw how to format dates according to some ISO and RCF standards. They can help you to quickly format a date in a standardised way. However, if you’re looking for date localisation then you’ll need something else.

By localising dates we mean that we want to show dates in an application according to the user’s region. A Japanese user will want to see the dates according to the Japanese date convention. You can store UTC dates internally according to an ISO standard but follow some local convention when presenting it on the screen.

Locales

A Locale represents a region and one or more corresponding cultures, most often with a country and one or more languages. You can easily list all available Locales:

Locale[] locales = Locale.getAvailableLocales();
        for (Locale locale : locales)
        {
            System.out.println(locale.getCountry());
            System.out.println(locale.getDisplayCountry());
            System.out.println(locale.getDisplayLanguage());
        }

You’ll see values such as…

PE
Peru
Spanish
ID
Indonesia
Indonesian
GB
United Kingdom
English

Some locales are stored as static properties of the Locale object, e.g.:

Locale.JAPAN
Locale.FRANCE
Locale.US

We’ll need to use the ZonedDateTime object to format a date according to a Locale. The following code will format the UTC date according to the US standard:

ZonedDateTime utcDateZoned = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.US);
System.out.println(utcDateZoned.format(pattern));

The output will be Friday, November 21, 2014 1:45:14 PM UTC.

Let’s see the UTC dates in France and Japan:

DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
System.out.println(utcDateZoned.format(pattern));

… vendredi 21 novembre 2014 13 h 50 UTC

DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.JAPAN);
System.out.println(utcDateZoned.format(pattern));

2014年11月21日 13時51分34秒 UTC

View all posts related to Java here.

Replacing a value in a Map in Java

The Java 8 SDK has a couple of interesting new default “replace” methods available on the Map interface.

Consider the following HashMap:

Map<String, String> sizes = new HashMap<>();
sizes.put("XS", "Extra small");
sizes.put("S", "Small");
sizes.put("M", "Medium");
sizes.put("L", "Large");
sizes.put("XL", "Extra large");
sizes.put("XXL", "Extra extra large");

Say we’d like to replace the value of key “S”:

String replacedValue = sizes.replace("S", "Small size");

The replace method returns the value of the replaced string. In the above case the key “S” will have a new value “Small size” and “replace” returns “Small” as it was the value of “S” before the replace operation.

Read more of this post

Extract information about the current method in Java

Say you wish to get some simple information about the currently running function in your Java program. The stacktrace of the current thread can help you find that.

Here’s a simple snippet to print the class name, the file name, the line number and the method name:

Read more of this post

Create a List using Arrays.asList in Java

Java 8 has a number of new methods on Collections. One such utility method is the static asList method with which you can quickly create a List of T.

Here’s how it works for a List of integers:

List<Integer> asList = Arrays.asList(1,2,3,4);

…and for a List of strings:

List<String> asList = Arrays.asList("hello", "my", "dear", "world");

View all posts related to Java here.

Adjusting the date in Java Date and Time API

Introduction

We saw a couple of new concepts in the Java 8 Date and Time API on this blog:

All the above classes expose methods called “with” with a couple of overloads. LocalDate, LocalTime and LocalDateTime come with other methods whose names start with “with”, such as withSeconds or withMonth depending on the supported level of time unit. The “with” methods adjust some value of the date-related instances and return a new instance.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.