java – Studytrails https://studytrails.com Follow the latest in AI Fri, 24 Aug 2018 00:43:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 Javadoc tool https://studytrails.com/2018/08/24/javadoc-tool/ https://studytrails.com/2018/08/24/javadoc-tool/#respond Fri, 24 Aug 2018 00:43:02 +0000 http://studytrails.com/?p=1630 Read more]]> Introduction to javadoc command

The javadoc tool is used to create nicely formatted documents from java source code. The tool can be found in the bin directory of java . The tool uses a ‘doclet’ to convert java source code into a document. The standard doclet produces an HTML document but you can have doclets that create pdf, postscript etc.

What can javadoc document?

javadoc looks for source files in the directory that you specify and documents all source files for the packages (and optionally subpackages) that you specify. It documents javadoc comments from public and protected classes, nested classes, interfaces, constructors (implicit too), methods and fields. It can add reference links to other pages. It creates a new document every time and does not create an incremental build.

What’s new in Java 9 javadoc?

javadocs created in java 9 are HTML5 compliant. Note that to be fully compliant any html written inside the javadoc comments have to be compliant too. Java 9 also adds a search box in the javadocs pages.

javadoc command

The image below shows a demo project with a single class.

javadoc tool example
javadoc tool example

To generate javadoc for this project, use this command

/usr/lib/jvm/jdk-10.0.1/bin/javadoc --source-path src/ -d ~/java/java9/doc/ com.st.java9

the –source-path specifies the path where the source files can be found. com.st.java9 is the name of the package that we want to document. All classes under this package will be documented. To include subpackages use –subpackages.
-d is used to specify the output folder where the documentation is created. look for ‘index.html’ file in this folder. This is the entry point to the documentation. The search box is located on top right.
This is how the search box looks like.

javadoc_search
javadoc_search

Javadoc has many other options that you can use such as adding a header/footer, or including types and members with a specific visibility (private, public, protectected) etc. The options can be divided into two types, the javadoc options and the doclet options. For more details on the options use javadoc --help

]]>
https://studytrails.com/2018/08/24/javadoc-tool/feed/ 0
Java 9 Jlink https://studytrails.com/2018/08/21/java-9-jlink/ https://studytrails.com/2018/08/21/java-9-jlink/#respond Tue, 21 Aug 2018 06:00:54 +0000 http://studytrails.com/?p=1626 Read more]]> What does the Java 9 JLink tool do

The java 9 JLink tool enables you to create a runtime application by assembling a specific set of modules. With this tool, Java 9 now has the capability to create an application that works even if you don’t have the JRE installed. JLink creates a minimal JRE required to run your application. It allows optimizing the runtime for the modules that you have included.

What are the advantages of Java 9 JLink tool

The JLink tool adds new functionalities and also opens up a few possibilities. Here are some of the advantages.

  1. The runtime image can be optimized since it is possible to optimize the custom application module along with the platform modules.
  2. Since the runtime created by jLink contains only the required modules, the size of the module is small. This opens up the possibility to use the application inside embedded and IOT devices.
  3. The user does not have to install the JRE
  4. Since the application image contains a subset of modules, it is safer from a security point of view since there would be fewer vulnerabilities

What are the disadvantages of Java 9 JLink tool

There are a few caveats to using the JLink tool.

  1. The application image once created, cannot be updated or patched. For any changes, a new application needs to be deployed
  2. When the user updates the JRE on her machine, the runtime image created by JLink does not get those updates and so any security fixes will not be applied.

Let us now look at an example of how to create a runtime image using JLink. We will create an application from the modules that we created as part of the modules tutorial here . We created the HelloWorldModule and HelloWorldModuleHelper that together take in a string and print “Hello World ” on the console. Lets take both the modules and built a runtime image out of it.

The image above shows how the two modules look like. To create the runtime image we use this command :

Java 9 Modules
Java 9 Modules

The jlink binary is inside the bin folder of the jdk.
–module-path specifies the path of the modules. In our example, we specify the path to the jvm modules and the path to our modules (.) separated by :
–add-modules tells the tool which modules should be the part of the runtime image. The tool adds the modules specified here plus all the modules that are required by this module recursively.
–launcher tells the tool that we need a launch script that will launch the runtime. If not specified, the tool will only create a java executable and we need to run the main class.
–output specifies the output directory where the runtime image would be created.
Once you run the command this is how the output directory looks like

Jlink output
Jlink output

To run the application cd to the “Hello” directory and type in “./bin/launch StudyTrails”. This will print “Hello World StudyTrails” on the console.

To summarize, JLink provides an optimal way to create a minimal runtime environment that can run with any external JRE. Its most promising use would be in IOT and embedded devices.

]]>
https://studytrails.com/2018/08/21/java-9-jlink/feed/ 0
Java 9 JShell https://studytrails.com/2018/08/21/java-9-jshell/ https://studytrails.com/2018/08/21/java-9-jshell/#respond Tue, 21 Aug 2018 05:11:02 +0000 http://studytrails.com/?p=1621 Read more]]> Java 9 JShell Command line tool.

The Java 9 JShell tool allows you to write and evaluate Java expressions, statements and declarations on the command line via an interactive tool. To start JShell type in ‘jshell’ on the command line. If that does not work, make sure you have installed JDK 9 or 10 and the bin folder is in classpath. The tool can be primarily used to quickly prototype functions and classes without going through the whole cycle of build, compile and run. Let’s look at some of JShell commands and concepts.

JShell Snippet

A JShell snippet is code that is written in jshell and evaluated independently. It can refer to a variable, method or class declaration, or an actual method call. Here are some examples

int x = 3

This declares an int variable called x. To list all variables use the command /vars>. To declare a class with a static method

public class Test {
public static int sum(int x, int y) {
   return x+y;
}
}

This is how the sum method is run

Test.sum(2,3)

JShell Commands

To list all the methods use /methods and to list all classes use /types.

JShell imports some packages and classes by default. To look at current imports type in </imports. A new import can be directly specified.
To list all the snippets entered so far use the /list command.

JShell Editor

JShell allows editing snippets in an external editor. To specify and editor type in

/set editor vim

To edit snippets type in /edit. To edit a particular snippet type in /edit [snippet_no] . Each snippet is given a number and that number can be use to reference the snippet

JShell shortcuts

JShell defines four shortcuts.

  • Tab – use the tab to autocomplete types, method suggestions or variables.
  • Use Shift+Tab followed by i to auto import. For example, When using java nio PIPE, we need to import the PIPE class. if you type in new PIPE followed by Shift+Tab and i, the tool will suggest imports
    jshell> JFrame
    0: Do nothing
    1: import: javax.swing.JFrame
    Choice: 
    Imported: javax.swing.JFrame
    
  • Shift+tab followed by v can be used to create a variable. In the example above if we fire this command after new JFrame, the tool allows use to define a new jframe variable
    jshell> new JFrame()
    jshell> JFrame jframe = new JFrame()
    
  • Shift+Tab followed by m can be used to create a method from an expression.
    jshell> 2+3
    jshell> int |() { return 2+3; }
    

    enter the name of the method where the cursor(|) is.

]]>
https://studytrails.com/2018/08/21/java-9-jshell/feed/ 0
Java 9 project coin language changes https://studytrails.com/2018/08/17/java-9-project-coin-language-changes/ https://studytrails.com/2018/08/17/java-9-project-coin-language-changes/#respond Fri, 17 Aug 2018 04:16:44 +0000 http://studytrails.com/?p=1618 Read more]]> The Java 9 project coin language changes include diamond with anonymous classes, private methods in interfaces, removing ‘_’ as a single character identifier, @SafeVargs on private instance methods and effectively final variables as resources in try-wth-resources statement.

1. Diamond with anonymous classes

Prior to Java 1.6, constructors did not have inferred type inference. This code would work in java 1.6

List<String> a = new ArrayList<String>();

but, omitting type on the constructor would not work.

List<String> a = new ArrayList<>();// does not compile.

java7 fixed that and we could use the diamond. However, the diamond can’t be used with anonymous classes. For example, lets create an anonymous classes

List<String> c = new ArrayList<>() {} 

This is an anonymous class that extends an ArrayList. This would not compile in Java 7 and Java 8, however, Java 9 allows this as part of project coin changes.

2. private methods in interfaces

Java 8 introduced the concept of default methods. These are methods in interfaces that have implementation.

package com.st.java9;

public interface PrivateMethods {

	int methodA();

	default void methodB() {}
	
	private void methodC() {}
}

In the example above methodB has an implementation and is a default method. methodC has an implementation but is a private method. They can be used by
other private methods and default methods in the interface.

3. Removing ‘_’ as a single character identifier

Versions prior to 9 allowed a variable called ‘_’ (underscore). Java 9 disallows that. Java 1.8 started using the underscore as a keyword and the compiler gave a warning. Java 9 gives a compile error.

4. @SafeVargs on private instance methods

When a method declares a method with parameterized variable argument, the compiler gives a warning . For example

public <T> void method1(T... a) {}

For this method the compiler gives a warning on a that says ‘Type safety: Potential heap pollution via varargs parameter a’. This is because java internally converts T… a to T[], but because java does not allow parameterized arrays the type is erased the it ends up as Object[]. This can potentially cause heap pollution. If you are sure that your method handles the vararg safely, you can annotate the method with @SafeVargs annotation and this will remove the compiler warning. Java 9 allows using the @SafeVargs annotation on private instance methods.

5. effectively final variables as resources in try-wth-resources statement

try-with-resources allows using auto-closeable objects inside the try block, so that they are automatically closed. For example, prior to Java9, this is how you would use a BufferedReader

BufferedReader reader = new BufferedReader(new FileReader(new File("")));
try (BufferedReader r1 = reader) {

}

However, with Java 9, you don’t need to redeclare a variable if it is final or effectively final.
This works with Java 9

BufferedReader reader = new BufferedReader(new FileReader(new File("")));
try (reader) {

}

However, note that the varialbe has to be effectively final or final, so this does not work.

BufferedReader reader = new BufferedReader(new FileReader(new File("")));
reader = new BufferedReader(new FileReader(new File("")));
try (reader) {

}

This completes our discussion on the language changes in Java 9. In the next article we will look at JLink tool.

]]>
https://studytrails.com/2018/08/17/java-9-project-coin-language-changes/feed/ 0
Java 9 Stack Walking API https://studytrails.com/2018/08/15/java-9-stack-walking-api/ https://studytrails.com/2018/08/15/java-9-stack-walking-api/#respond Wed, 15 Aug 2018 06:13:17 +0000 http://studytrails.com/?p=1599 Read more]]> What is the Stack Walking API

The Java 9 Stack walking API provides an efficient way to walk the jvm stack. The existing methods Thread::getStackTrace() and Throwable::getStackTrace return an array of all stack frames and they do that by grabbing all the frames in the stack. This is performance intensive. The implementation is also allowed to skip a few frames in order to speed up the process. The Stack Walking API allows lazily grabbing frames and also filtering frames based on criteria. The user can choose to walk only a few frames until her criterion is matched or walk the whole frame.

The stack elements are reported in order, starting from the topmost frame. The walk method gives a Stream of StackFrames.

It is possible to pass options to the frame in order to return specific information.

Examples of using the Stack Walking API.

Let’s look at an example of the stack walking API.

Example of StackWalking API

package com.st.java9;

public class ThreadStackWalker {

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new ClassA());
		t.start();

		Thread.sleep(1000);
		Thread t2 = new Thread(new ClassB());
		t2.start();
	}

}

class ClassA implements Runnable {
	@Override
	public void run() {
		StackWalker.getInstance().walk(s -> s.peek(System.out::println).count());
		System.out.println("-----------------------------");
	}
}

class ClassB implements Runnable {
	@Override
	public void run() {
		StackWalker.getInstance().walk(s -> s
				.filter(a -> a
						.toStackTraceElement().getClassName().contains("java9"))
				.peek(System.out::println).count());
		System.out.println("-----------------------------");
	}
}
#output
com.st.java9.ClassA.run(ThreadStackWalker.java:19)
java.base/java.lang.Thread.run(Thread.java:844)
-----------------------------
com.st.java9.ClassB.run(ThreadStackWalker.java:27)
-----------------------------

In the example above we create two classes ClassA and ClassB that implement Runnable. We create an instance of both threads and start them. For ClassA we walk the stack and print all the frame classes. For ClassB we walk the stack and filter out the frames so that it contains classes that have ‘java9’ in their fully qualified name.

Stack Walking API Creation Options

The StackWalker class takes in 3 different types of options.

  1. StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE) – This allows the StackWalker to support the StackFrame.getDeclaringClass() and StackFrame.getCallerClass() method
  2. StackWalker.getInstance(Option.SHOW_REFLECT_FRAMES) – The reflection frames are hidden by default. This option allows showing the hidden frames.
  3. StackWalker.getInstance(Option.SHOW_HIDDEN_FRAMES) – In addition to the reflection frames some jvm implementation hides the implementation specific frames. This option shows the implementation specific frames.

This completes our discussion on the StackWalking API. In the next article, we look at the project coin changes, specifically the private interface methods.

]]>
https://studytrails.com/2018/08/15/java-9-stack-walking-api/feed/ 0
Java 9 Enhancements to Stream and java.util.Arrays https://studytrails.com/2018/08/14/java-9-stream-arrays-enhancements/ https://studytrails.com/2018/08/14/java-9-stream-arrays-enhancements/#respond Tue, 14 Aug 2018 06:30:00 +0000 http://studytrails.com/?p=1596 Read more]]> In this tutorial we will cover the Java 9 enhancements to Stream and java.util.Arrays. The most important enhancements to stream are the takeWhile, dropWhile, ofNullable, and iterate methods. The enhancement to Arrays has been the new equals and mismatch method that allow comparing subset of arrays.

We will look into the details of the new methods below.

Java 9 Enhancements to Stream

Stream<T> takeWhile(Predicate<? super T> predicate)

For ordered stream this method returns the longest prefix of the stream that matches the predicate function. For unordered stream the method returns a subset of elements of the stream that match the given predicate. For unordered stream the function may return any subset that matches the given predicate. This method can be best explained by an example.

jshell< List<Integer> a=List.of(1,2,3,4,5,6,7,8,9)
a ==> [1, 2, 3, 4, 5, 6, 7, 8, 9]
jshell> a.stream().takeWhile(a->{return a<5;}).collect(Collectors.toList())

In the example above, we create a stream of elements 1 to 9. The takeWhile operation then ‘takes’ a subset from this list such that all elements in the subset are allowed by the predicate (i.e. subset of all elements less than 5 )

Stream<T> dropWhile(Predicate<? super T> predicate)

In Contrast to takeWhile, the dropWhile operation drops the longest prefix of the stream that matches the given predicate and returns the other elements.

a ==> [1, 2, 3, 4, 5, 6, 7, 8, 9]
jshell> a.stream().dropWhile(a->{return a<5;}).collect(Collectors.toList())
$11 ==> [5, 6, 7, 8, 9]

static<T> Stream<T> ofNullable(T t)

This method returns a stream containing a single element if t is not null and zero elements if t is null.

jshell> Stream.ofNullable(null).count()
$18 ==> 0

jshell> Stream.ofNullable(1).count()
$19 ==> 1 

static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

The iterate function is used to return a stream whose elements are obtained by iteratively applying the next function to the previous element (starting with the seed element) as long as the hasNext predicate returns true. Here’s an example

jshell> Stream.iterate(1L, n->{ return n<5;}, n -> { return n + 1;})
                                .collect(Collectors.toList())
$3 ==> [1, 2, 3, 4]

In the example above we increment the previous element by 1 (next => n +1) as long as n < 5 (hasNext). The first element is 1 (seed). We can even generate an infinite stream.

jshell> Stream.iterate(1L, n -> { return n + 1;}).limit(10)
                               .collect(Collectors.toList())
$4 ==> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We now look into the new methods added in java.util.Arrays

Java 9 enhancements to java.util.Arrays

Java 9 adds a suite of equals methods to Arrays. This article looks at some of those methods

static boolean equals(double[] a, int aFromIndex, int aToIndex,
double[] b, int bFromIndex, int bToIndex)

This method returns true if two arrays are equal over the specified range.
example:

jshell> Arrays.equals(new double[] {8,1,2,3,4,5},1,4,new double[]{5,1,2,3,6,7},1,4)
$14 ==> true

In the example above we compare the first to fourth element of two arrays.
if we include the fifth element in the comparison, the method should return false.

jshell> Arrays.equals(new double[] {8,1,2,3,4,5},1,5,new double[]{5,1,2,3,6,7},1,5)
$15 ==> false

It is possible to compare different subsets (of same length) from each array

jshell> Arrays.equals(new double[] {8,1,2,3,4,5},1,4,new double[]{3,5,1,2,3,6,7},2,5)
$16 ==> true

In this example we compare the first to fourth elements for first array to the 2nd to 5th elements of the second array.

static int mismatch(double[] a, int aFromIndex, int aToIndex,
double[] b, int bFromIndex, int bToIndex)

Returns the index of the first mismatch between two arrays over the specified index ranges.Returns -1 if there is no mismatch

jshell> Arrays.mismatch(new double[]{1,2,3,5,6,7},new double[]{1,2,3})
$46 ==> 3
jshell> Arrays.mismatch(new double[]{1,2,3,5,6,7},0,2,new double[]{1,2,3},0,2)
$47 ==> -1

There are equivalent methods for other types too. They are similar to the ‘double’ methods that we have covered here.

This completes our tutorial on the Java 9 Enhancements to stream and java.util.arrays. In the next article we will look at the stack walking API.

]]>
https://studytrails.com/2018/08/14/java-9-stream-arrays-enhancements/feed/ 0
Java 9 Collection factory and java 10 copyOf methods https://studytrails.com/2018/08/01/java-9-collection-factory-and-java-10-copyof-methods/ https://studytrails.com/2018/08/01/java-9-collection-factory-and-java-10-copyof-methods/#respond Wed, 01 Aug 2018 05:53:23 +0000 http://studytrails.com/?p=1568 Read more]]> The Java 9 collection factory methods and java 10 copyOf methods add functionalities to create immutableCollections. Before we discuss those methods, let us look at three concepts in collections i.e. View Collection, Unmodifiable collection and unmodifiable view collection.

What is a View Collection?

A view collection does not store elements but instead relies on a backing collection. It provides a few specific methods and delegates to the backing collection for other methods. There are two groups of View Collections. The first group contains wrapper collections and they extend the contract of the collections by making them more specific. For example, Collections.checkedCollection creates a typesafe view of the collection. The second group provides a different representation of the same elements. For example, List.subList provides a view of elements between a startIndex and endIndex. Any changes to the backing collection are reflected in the view and any permitted changes through the view are carried to the backing collection.

What is an Unmodifiable Collection?

An Unmodifiable Collection is a collection that throws an UnsupportedOperationException when any of the mutator methods are called. A mutator method attempts to change the state of the Collection by adding, modifying or deleting entries from it. If the entries of the collection are itself mutable then unmodifiable collection cannot be considered completely mutable. For example, consider an unmodifiable list of addresses. Since the actual address object can be modified outside the collection, the list is considered mutable. Only if all the elements of the list are unmutable, the list is considered effectively unmutable. e.g. java.util.Collections.UnmodifiableList

What is an Unmodifiable View Collection?

An unmodifiable View Collection is an unmodifiable collection that is backed by another collection. It, therefore, provides a read only view into the backing collection. e.g. Collections.unmodifiableCollection. Its mutator methods throw an exception and the accessor methods are delegated to the backing collection.

With that out of the way, let us now look at the new methods added in Java 9 and 10.

collection factory methods in java.util.List

  • static <E> List<E> of()

    Creates an empty immutable list. If we try to add another element to the list, we will get an UnsupportedException

    List<String> items  = List.of();
    //items.add("should throw an error"); 
    // throws java.lang.UnsupportedOperationException
    
  • static <E> List<E> of(E e1)

    Creates an immutable list with one element. There are methods to add upto 10 elements in the list. i.e. with two elements the method looks like

     static <E> List<E> of(E e1, E e2)

    With 10 elements it looks like

    static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
  • static <E> List<E> of(E... elements)
    

    This method creates an unmodifiableList containing a variable number of arguments.

  •  static <E> List<E> copyOf(Collection<? extends E> coll)
    

    This method was added in Java 10. This method creates an unmodifiableList copy of the given collection. The copy maintains the iteration order.

Collection factory methods in java.util.Map

Map adds new methods similar to the list. Here’s a method that creates an unmodifiable Map with one element.

  • static <K, V> Map<K, V> of(K k1, V v1)
    

    There are similar method for upto 10 key value pairs.

  • static <K, V> Map<K, V> ofEntries(Entry<? extends K, ? extends V>... entries)
    

    This method gets the key value from the entries and adds it to an unmodifiable map. It does not add the actual Entry.

  • static <K, V> Entry<K, V> entry(K k, V v)
    

    This creates an unmodifiable Entry using the key value pair.

  • static <K, V> Map<K, V> copyOf(Map<? extends K, ? extends V> map)
    

    This method was added in java 10 and creates a immutable map from another map. Changes made to the original map are not reflected in the immutable map.

  • Collection factory methods in java.util.Set

  • The set interface has methods similar to the List interface with the ‘of()’ methods to create unmodifiable Set from 0 to 10 elements and copyOf method to create an unmodifiable copy.
]]>
https://studytrails.com/2018/08/01/java-9-collection-factory-and-java-10-copyof-methods/feed/ 0
Java 9 Reactive Streams https://studytrails.com/2018/07/30/java-9-reactive-streams/ https://studytrails.com/2018/07/30/java-9-reactive-streams/#respond Mon, 30 Jul 2018 06:11:42 +0000 http://studytrails.com/?p=1529 Read more]]> Java 9 Reactive Streams contain a set of interfaces that follow the reactive streams specification.
This article is a part of series of articles that contain the features in Java 9. here is the list of changes.

  1. Java platform module system
  2. JShell – Interactive command line tool
  3. Reactive Streams
  4. Factory method for Collections
  5. Enhancements in Stream, CompletableFuture, java.util.Arrays, Stack walking API
  6. Project coin changes – e.g. private interface methods
  7. Jlink – tool to assemble modules
  8. Documentation updates, HTML5, javadoc search
  9. Process API changes, new internal representation for String
  10. Parser API for Nashorn
  11. MRJAR – Multi Release Jar

Before we describe the interfaces, lets look at some basic concepts:

What are reactive streams?

Reactive programming is based on the Reactive manifesto and primarily deals with asynchronously handling a stream of data . To give you an example, consider a weather mobile App that obtains data from a RESTful API. When the user clicks on a link, the process in the background kicks of a call to an API. However, instead of waiting for the response, the process simply returns back and another thread ‘subscribes’ to the API response. If the API returns an years worth of temperature data for plotting on a graph, it makes sense to render the data that has been obtained so far and continue subscribing for more data. The advantage is that the screen does not become unresponsive and the app can load a huge volume of data incrementally.
Before we explain a few other concepts, lets look at how the Java 9 reactive API is different from other reactive APIs such as RxJava.

Java 9 Reactive API vs RxJava

To answer this question, we need a bit of background. Some of the pioneers in reactive programming in java such as RxJava (1.x) and the Reactor project by Spring started developing their own implementation of the reactive manifesto and people soon realized that a common specification was needed. This gave birth to Reactive Streams. The Reactive streams describe a set of interfaces that enable asynchronous stream processing and non blocking backpressure (see below). Since RxJava 1.x could not be retrofitted to follow these interfaces, RxJava 2 was introduced. At the same time, the interfaces were incorporated into the Java specification in Java 9.
So the difference between Java 9 Reactive API and RxJava 2 is that the former specifies interfaces that follow the Reactive Stream discussions whereas the later implements those interfaces and scores of other methods that allow efficient handling of reactive streams.

What is asynchronous processing and non blocking backpressure

The whole idea of Reactive Streams is that the stream is handled asynchronously. I.e. the stream destination runs on a separate thread from the stream source. An obvious problem is what happens if the source emits more items than the destination can process? In such cases, backpressure implies that the destination does not accept more items than it can process and somehow signals upstream that it cannot handle more item (or asks for only a quantity of items that it can process). The backpressure has to be non blocking since the act of passing the backpressure message to the source should itself be asynchronous.

Java 9 Reactive Streams

There are four core interfaces in Java 9 Reactive Streams. The idea is that instead of the source (publisher) pushing items to the destination (subscriber), the subscriber asks for a certain number of items which the publisher sends as and when they are available. A subscriber subscribes to a publisher through a subscribe() method of the publisher. Here are the interfaces:

Java 9 Reactive Stream interfaces

public static interface Publisher<T> {
  public void subscribe(Subscriber<? super T> subscriber);
}
public static interface Subscriber<T> {
  public void onSubscribe(Subscription subscription);
  public void onNext(T item);
  public void onError(Throwable throwable);
  public void onComplete();
}

The interface that joins the Publisher and the Subscriber is called ‘Subscription’.

public static interface Subscription {
  public void request(long n);
  public void cancel();
}

The fourth interfaces is used to process items as they move from a Publisher to a Subscriber and consequently implements both the interfaces.

public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
}

Overview of the reactive implementation

Java 9 Reactive Stream
Java 9 Reactive Stream
.
The steps in a Reactive application are:

  1. The Publisher subscribes a Subscriber using the ‘subscribe’ method of the publiser. ((1) in diagram above)
  2. The subscriber requests for ‘n’ items from the publisher ((2) in diagram above)
  3. The publisher sends an item to the subscriber asynchronously when it can. ( (3) in diagram above). The publisher maintains a buffer so that if the subscriber cannot process an item, the publisher keeps it in its buffer. It can either try again or discard some items for a subscriber

The JDK provides an implementation of the Publisher interface called ‘SubmissionPublisher’.
Here’s an example that uses SubmissionPublisher to create a publisher that emit temperature values. We create a SubmissionPublisher that publishes 9 values to the subscriber. The subscriber requests for 3 values initially and once it receives them, it asks for three more. In this example, we simulate a 0.5s processing time for each item that the subscriber receives. Since the publisher sends all items at once, it will have to buffer some items while the subscriber is processing it.

Here are the classes:
The Publisher:

package com.st.java9;

import java.util.concurrent.SubmissionPublisher;

public class Reactive {

	public static void main(String[] args) throws InterruptedException {
		// create a submission publisher
		SubmissionPublisher<Double> submissionPublisher = new SubmissionPublisher<>();
		submissionPublisher.subscribe(new TemperatureSubscriber());
		for (int i = 0; i < 9; i++) {
			// submit a randomly generated temperature value
			double value = Math.random() * 30;
			System.out.println("Submitting " + i + ":" + value);
			submissionPublisher.submit(value);
		}
		submissionPublisher.close();
	}
}

The Subscriber

package com.st.java9;

import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;

public class TemperatureSubscriber implements Subscriber<Double> {

	private Subscription subscription;
	int pending = 0;
	int requests = 3;

	@Override
	public void onNext(Double item) {
		try {

			// stimulate an operation that takes 5s.
			Thread.sleep(500);
			System.out.println("Consuming " + Reactive.format.format(item));
			pending--;
			// start requesting more if only 1 or less is pending from the previous request.
			if (pending < 1) {
				System.out.println("Requesting " + requests);
				subscription.request(requests);
				pending = requests;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onError(Throwable throwable) {
		System.out.println(throwable.getMessage());
	}

	@Override
	public void onComplete() {
		System.out.println("Done");
	}

	@Override
	public void onSubscribe(Subscription subscription) {
		this.subscription = subscription;
		// request the first batch
		subscription.request(requests);
		pending = requests;
	}
}

Here’s how the output looks when run

The SubmissionPublisher has a few other methods too which we will cover in a later tutorial.

Conclusion to Java 9 Reactive Streams

Java 9 introduced 4 new interfaces for Reactive Stream processing and an implementation of a Publisher. The idea is that more libraries will start adhering to the reactive standard specified by this libraries. The Flow classes in RxJava2 already implement them and so do the Reactor framework by Spring.

]]>
https://studytrails.com/2018/07/30/java-9-reactive-streams/feed/ 0
Java 9 Platform Module system https://studytrails.com/2018/07/23/java-9-platform-module-system/ https://studytrails.com/2018/07/23/java-9-platform-module-system/#respond Mon, 23 Jul 2018 05:18:18 +0000 http://studytrails.com/?p=1503 Read more]]> Java 9 Platform Module System

Java 9 Platform Module System introduces the concept of modules that allow breaking up a project into logical parts. Modules provide better configuration and greater encapsulation. A module consists of classes and interfaces and a configuration file known as module-info.java. Module A can access only those members of Module B that have been exported by Module B. To specify that Module A needs Module B, we use the ‘requires’ keyword in the Module A configuration file. To specify all packages exported by a module we use the “exports” keyword in module-info.java file.
Lets look at an example of the module system using a ‘Hello World’ Example.

Example of Java 9 Platform Modules System

We write a class that prints Hello World followed by the name of a person.

package com.st.HelloWorldModule;

import com.st.HelloWorldModuleHelper.HelloWorldHelper;
public class HelloWorld {
    public static void main(String[] args) {
       HelloWorldHelper helper = new HelloWorldHelper();
       System.out.println(helper.decorate(args[0]));
   }
}

Since printing Hello World followed by a name is a fairly complex operation 🙂 , we create a helper class that decorates the name to create the string ‘Hello World Mithil’

package com.st.HelloWorldModuleHelper;

public class HelloWorldHelper {

   public String decorate(String name) {
      return "Hello World "+name;
   }
}

Note that the helper class is in a package called HelloWorldModuleHelper, whereas the HelloWorld class in a package called HelloWorldHelper. Normally, this would work fine. Here’s how we compile and run the class

cd ~/java/java9/modules/HelloWorldModuleHelper
javac -d ~/java/java9/modules/output/HelloWorldModuleHelper com/st/HelloWorldModuleHelper/HelloWorldHelper.java
cd ~/java/java9/modules/HelloWorldModule
javac -cp ~/java/java9/modules/output/HelloWorldModuleHelper/ -d ~/java/java9/modules/output/HelloWorldModule com/st/HelloWorldModule/HelloWorld.java

In line 2 we compile the HelloWorldHelper class and put the class files in output/HelloWorldModuleHelper directory.
In line 4 we compile the HelloWorld class and put the HelloWorldHelper class in the classpath.
To run the HelloWorld class do this:

cd ~/java/java9/modules/output
java -cp .:../HelloWorldModuleHelper/ com.st.HelloWorldModule.HelloWorld Mithil
Hello World Mithil

We run the HelloWorld class and put the Helper in classpath and all works well.
Its time now to introduce modules. We want to create two modules, one for the HelloWorld class and other for the HelloWorldHelper class.
Here’s how the module-info.java class for HelloWorldHelper looks like

module com.st.HelloWorldModuleHelper{
 exports com.st.HelloWorldModuleHelper; 
}

To use this module in HelloWorldModule we will need to use the ‘requires keyword’

module com.st.HelloWorldModule {
	requires com.st.HelloWorldModuleHelper;
}

To specify which modules are included during compilation we specify the –module-path to javac and java

cd HelloWorldModuleHelper
javac -d ../output/HelloWorldModuleHelper com/st/HelloWorldModuleHelper/HelloWorldHelper.java
javac -d ../output/HelloWorldModuleHelper module-info.java

cd HelloWorldModule
javac -d ../output/HelloWorldModule --module-path ../output/HelloWorldModuleHelper/ module-info.java
javac -d ../output/HelloWorldModule --module-path ../output/HelloWorldModuleHelper/ com/st/HelloWorldModule/HelloWorld.java

cd output/HelloWorldModule
java --module-path ~/java/java9/modulesCourse/output -m com.st.HelloWorldModule/com.st.HelloWorldModule.HelloWorld Mithil

In line 3 we compile the module-info.java class, just like any other java class.
In line 6 we include the module path in javac using –module-path.
In line 10 we include the module path in java using –module-path. The result of running this program would be
‘Hello World Mithil’

This is how the directory structure now looks like

Modules_Directory_Structure
Modules_Directory_Structure

If you were to remove the ‘requires’ line from module-info.java, you would see this error:

com/st/HelloWorldModule/HelloWorld.java:3: error: package com.st.HelloWorldModuleHelper does not exist

The platform module system is a fundamental change to the Java language specification. In the next tutorial we will look at the JShell tool which is a very handy tool for rapid development and prototyping.

]]>
https://studytrails.com/2018/07/23/java-9-platform-module-system/feed/ 0
Download Java Source Code https://studytrails.com/2018/07/06/download-java-source-code/ https://studytrails.com/2018/07/06/download-java-source-code/#respond Fri, 06 Jul 2018 05:39:19 +0000 http://studytrails.com/?p=1514 If you are looking to download java source code then this links will help you :

Download Java Source Code for JDK 10

https://download.java.net/openjdk/jdk10/ri/openjdk-10_src.zip

Download Java Source Code for JDK 9

https://download.java.net/openjdk/jdk9/ri/openjdk-9_src.zip

Download Java source code for JDK 8

https://download.java.net/openjdk/jdk8u40/ri/openjdk-8u40-src-b25-10_feb_2015.zip

]]>
https://studytrails.com/2018/07/06/download-java-source-code/feed/ 0