Monday, January 1, 2018

Java 9 for Beginners

Modularity
Modularity is a general concept. In software, it applies to writing and implementing a program or computing system as a number of unique modules, rather than as a single, monolithic design.

The major change in Java 9 is the module System that has already been implemented in Java 9. The module system was introduced to make jdk scalable to smaller devices. The module system will provide application the capability to use only the jdk modules that are needed. The applications will no longer need the whole jdk framework. The module system will also encapsulate the public classes within a module. So a class defined public would not be available to the whole world until a module explicitly defines so. Because of this change the internal api e.g. com.sun.* of java will not be available anymore by default.

Simply put, the modules are going to be described in a file called module-info.java located in the top of java code hierarchy:

module me.aboullaite.java9.modules.car
{
requires me.aboullaite.java9.modules.engines;
exports me.aboullaite.java9.modules.car.handling;
}

Collection Factory methods


Before Java 9, it was possible to create an immutable view of the collections but only with some utility methods e.g. Collections.unmodifiableCollection(Collection<? extends T> c). For example, Let us create an immutable view of Collection in Java 8, with a one liner. This is the easiest way to do so in Java 8. It looks bad! isn't ?
Map<String, String> immutableMap = 
Collections.unmodifiableMap(
           new HashMap<String, String>() {{
             put("key1", "Value1");
             put("key2", "Value2");
             put("key3", "Value3");
         }});

Java 9 brings Now, something useful with the factory methods for creating immutable collections. Lets us now create the immutable Map in Java 9.
Map<String, String> immutableMap = Map.of("key1", "Value1", "key2", "Value2", "key3", "Value3");

Here are the examples of the factory methods:
    // empty immutable collections
    List<String> emptyImmutableList = List.of();
    Set<String> emptyImmutableSet = Set.of();
    Map emptyImmutableMap = Map.of();

    // immutable collections
    List<String> immutableList = List.of("one", "two");
    Set<String> immutableSet = Set.of("value1", "value2");
    Map<String, String> immutableMap = Map.of("key1", "Value1", "key2", "Value2", "key3", "Value3");


Improved Javadoc
Currently, if you want to find some class documentation you have to search in google. In Java 9 there are several improvements to the Javadoc and one of them is the addition of a search box.




Process API Improvements

So far there has been a limited ability for controlling and managing operating system processes with Java. For example, in order to do something as simple as get your process PID today, you would need to either access native code or use some sort of a workaround. More than that, it would require a different implementation for each platform to guarantee you’re getting the right result.

In Java 9, expect the code for retrieving Linux PIDs, that now looks like this:
    public static void main(String[] args) throws Exception
    {
    Process proc = Runtime.getRuntime().exec(new String[]{ "/bin/sh", "-c", "echo $PPID" });

    if (proc.waitFor() == 0)
    {
    InputStream in = proc.getInputStream();
    int available = in.available();
    byte[] outputBytes = new byte[available];

    in.read(outputBytes);
    String pid = new String(outputBytes);

    System.out.println("Your pid is " + pid);
    }
    }



To turn into something like this (that also supports all operating systems):

System.out.println("Your pid is " + Process.getCurrentPid());

The update will extend Java’s ability to to interact with the operating system: New direct methods to handle PIDs, process names and states, and ability to enumerate JVMs and processes and more.


Money and Currency API

After the new Date and Time API introduced in Java 8, Java 9 brings with it a new and official API for representing, transporting, and performing comprehensive calculations with Money and Currency. To find out more about the project, you can visit JavaMoney on Github. Code and usage examples are already available right here . Here are a few highlights:


Money amt1 = Money.of(10.1234556123456789, "USD"); // Money is a BigDecimal
FastMoney amt2 = FastMoney.of(123456789, "USD"); // FastMoney is up to 5 decimal places
Money total = amt1.add(amt2);


The new money types: Money & FastMoney

MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMANY);
System.out.println(germanFormat.format(monetaryAmount)); // 1.202,12 USD
Formatting money according to different countries


Diamond Operator Scope Extension

Java 7 gave us diamond operator to make our lives bit easier.In the below example you can see that java 7 list is more readable and concise.

List<String> preJava7 = new ArrayList<String>();
List<String> java7 = new ArrayList<>();

But Java 7 diamond operator was not allowed on anonymous classes.

But Java 9 has enhanced the Diamond operator to work even on anonymous classes. The below example will only compile in Java 9

List<String> list = new ArrayList<>(){ };


Private Methods in Interfaces



Java 8 allowed you to write default methods in interfaces, and it was widely appreciated feature. So after this, interfaces only lack few things and only non-private methods was one of them. Java 9 onward, you are allowed to include private methods in interfaces.
These private methods will improve code re-usability inside interfaces. Foe example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.
Using private methods in interfaces have four rules :
1. Private interface method cannot be abstract.
2. Private method can be used only inside interface.
3. Private static method can be used inside other static and non-static interface methods.
4. Private non-static methods cannot be used inside private static methods.

interface InterfaceWithPrivateMethods {
private static String staticPrivate() {
return "static private";
}

private String instancePrivate() {
return "instance private";
}

default void check() {
String result = staticPrivate();
InterfaceWithPrivateMethods pvt = new InterfaceWithPrivateMethods() { // anonymous class
};
result = pvt.instancePrivate();
}
}}



JShell Command Line Tool

JSJshell is read–eval–print loop – REPL for short.
Simply put, it’s an interactive tool to evaluate declarations, statements, and expressions of Java, together with an API. It is very convenient for testing small code snippets, which otherwise require creating a new class with the main method.

The jshell executable itself can be found in <JAVA_HOME>/bin folder:
jdk-9\bin>jshell.exe
| Welcome to JShell -- Version 9
| For an introduction type: /help intro
jshell>2 + 2

| Expression value is: 4


New Version String Format

Semantic versioning is the message here. In the new Java version, a new version scheme was defined as described below:

Major.Minor.Security.Patch, where:

• Major: $MAJOR version, when you make incompatible API changes.
• Minor: $MINOR version, when you add functionality in a backward-compatible manner.
• Security: $SECURITY version, when you add security-critical fixes, including those necessary to improve security functionality or make backward-compatible bug fixes.
• Patch: $PATCH version, when you make backward-compatible bug fixes.

With microservices projects, this feature could foster a new way to control the versioning and evolution of projects and solutions — with a clear view of what’s inside of it when this pattern is rigorously followed.



Reactive streams
Currently, the Reactive Programming is popular in developing applications to gain some great benefits. The likes of Scala, Play and Akka frameworks have joined the Reactive Streams.
Oracle is also announcing new Reactive Streams API in Java 9. These new Reactive Streams API is a Publish or Subscribe Framework to implement Asynchronous, Scalable and Parallel applications easily using Java language.

Reactive Streams

The Flow APIs in JDK 9 correspond to the Reactive Streams Specification, which is a defacto standard. JEP 266 contains a minimal set of interfaces that capture the heart of asynchronous publication and subscription. The hope is that in the future 3rd parties will implement them and thus convene on a shared set of types.

The class java.util.concurrent.Flow encloses the following 4 interfaces
Flow.Processor
Flow.Publisher
Flow.Subscriber
Flow.Subscription
These interfaces support the Reactive Streams publish-subscribe framework. Java 9 also provides a utility class SubmissionPublisher. A Publisher produces items that are consumed by a number of Subscribers. And a Subscriber is managed by a Subscription. Subscription links the Publisher and Subscriber.



HTTP/2 Client
HTTP/1.1 client was released on 1997. A lot has changed since. So for Java 9 a new API been introduced that is cleaner and clearer to use and which also adds support for HTTP/2. New API uses 3 major classes i.e. HttpClientHttpRequest and HttpResponse.
To make a request, it is as simple as getting your client, building a request and sending it as shown below.
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder().uri(newURI("//:javafungus.blogspot.com")).GET().build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());
System.out.println( httpResponse.body() );
Above code looks much cleaner and readable.
New API also support Async HTTP requests using httpClient.sendAsync() method. It returns CompletableFuture object which can be used to determine whether the request has been completed or not. It also provide you access to the HttpResponse once request is completed. Best part is that if you desire you can even cancel the request before it completes. e.g.
if(httpResponse.isDone()) {
    System.out.println(httpResponse.get().statusCode());
    System.out.println(httpResponse.get().body());
else {
    httpResponse.cancel(true);
}


Technical Writing in field of research

Research reports A research report is a collection of contextual data, gathered through organized research, that provides new insights into ...