Java 9 : Convenience Factory Methods to create immutable Collections

Java 9

                             In this article we will see another JDK 9 feature to create immutable collections. Till Java 8, If we want to create immutable collections we use to call unmodifiableXXX() methods on java.util.Collections class. For example,  To create unmodifiable list, we should write below code.

The above code is too verbose to create a simple unmodifiable List. As Java is adopting functional programming style Java 9 came up with convenience, more compacted factory methods to create unmodifiable collections with JEP 269. Let us see how  that works.

Create Empty List:

Create Non-Empty List:

Create Non-Empty Map:

If you look at the above Java 9 factory method, the code is simple one liner to create immutable collections. In the coming article we will see another Java 9 feature. Till then, Stay Tuned!!!

Advertisements
Tagged with: ,
Posted in Java

jshell: The Java Shell (Read-Eval-Print Loop)

Java 9

                         In this article we will discuss about jshell(Java Shell) Java 9 feature. We can explore jShell with JDK 9 Early Access Release.  As of now the general availability of JDK9 is scheduled to 27th July, 2017. The jShell feature is proposed as part of JEP 222. The motivation behind jshell is to provide interactive command line tools to explore the features of java quickly. It is very useful tool to get the glimpse of Java features very quickly for the new learners. Already Java is incorporating functional programming features from Scala. In the same direction they want REPL(Read-Eval-Print Loop) interactive shell for Java as Scala, Ruby, JavaScript, Haskell, Clojure, and Python.

                       The jshell tool will be a command-line tool with features like, a history of statements with editing, tab completion, automatic addition of needed terminal semicolons, and configurable predefined imports.

After downloading the JDK 9, set the PATH variable to access jshell. Now, we will see how to use jshell. Below is the simple program using jshell. We no need to write a class with public static void main(String[] args) method to run simple hello world application.

Now we will write method which will add two variables and invoke method via jshell.

Now, we will create a static method with StringBuilder class without importing it, as jshell does that for you.

I hope you enjoyed jshell feature. In the next article we  will see another JDK 9 feature. Till then, Stay Tuned!!!

Tagged with: , ,
Posted in Java

Software Architecture – Hexagonal Architecture Pattern

software_architecture_patterns

                     In this article we will see “Hexagonal Architectural Pattern” also known as “Ports and Adapters” pattern. As developers so far we have created applications with tiered architecture styles like MVC (Model View Controller). With this architectural styles, up to certain extent we were able to decouple the domain logic with other functionalities. At times the domain logic use to leak into UI or other functionalities. As the core logic is getting leaked into other layers , the impact of the code change will have ripple effect on other modules. To avoid this we can go with “Ports and Adapters” architecture style.

                      The “Ports and Adapters” style will have domain logic as Core and the Adapters will have the application logic specific  to translate an interface from outside request  into a compatible one. The core and the adapters sits as inner layer. The ports sits on outer layer to interact with the external services. The below diagram depicts the above said architectural style.

hexagonal-architecture

                        The advantages of this style is the core logic abstracted from the out side world. The code is decoupled via the adapters. We can add or remove the new functionalities easily. We can perform testing of core logic and the adapters in isolation mode.

                      In the coming article we will see what is micro services architectural style? and what are the driving factors behind it? Till then Stay Tune!!!

Tagged with: ,
Posted in Design Patterns

Gatling – Integration with Maven

gatling-logo

                                               In this article we will see how to use Gatling with Maven. This approach enables us to integrate Gatling as part of continuous integration. Along with that we will see how to externalize properties used in simulation script and the dynamic data feeding using Gatling feeders. Let us see the above said features in action.

As a first step create a maven project and add the below Gatling dependencies.

Now, we will externalize the baseURL property used in our simulation. For this add the application.properties file under src/test/resources and use ConfigFactory to get access to the properties. The sample simulation is given below.

Now, we will see how to add dynamic data used as part of simulation. For this I am using Gatling’s CSVFeeder. You can get more info on Gatling’s feeders http://gatling.io/docs/2.2.3/session/feeder.html. Add the feeder file under src/test/resources/data. The sample simulation using csv feeder is given below.

Run mvn gatling:execute to execute Gatling project which will run the simulations. The entire project used for this article is available on GitHub.

Gatling Maven Demo

Tagged with: , ,
Posted in Testing

Gatling – Light weight load testing tool

gatling-logo

                                   Gatling is a light weight stress testing tool backed by Scala, Akka and Netty. It  works asynchronously if the under lying HTTP request is non blocking. It uses messages for virtual user simulation than thread per virtual user. Because of this it consumes lesser system resources to run load test. In this article let us see a REST endpoint load testing by following the below steps.

Step 1: Download the Gatling bundle from http://gatling.io/#/resources/download . The folder structure of GATLING_HOME is explained below.

gatling_folder_structure

Step 2: Set GATLING_HOME and JAVA_HOME environment variables and write a sample simulation using Scala. As a java developer you no need to have strong Scala knowledge to write Gatling simulations with Scala. We need to have very basic knowledge. A simulation is given below to test a REST end point.

                     In the above simulation we are ramping up the 1000 users in 10 seconds. Once the simulation script is ready, go to the bin folder and launch the gatling.bat/gatling.sh. The script will run the simulation available under “simulations” folder and generates the reports under results folder.

The sample report is given below.

gatling_performance_stats

In the coming article we will see how to use Gatling maven integration and additional features like feeders, externalizing the properties etc… Till then, Stay Tune!!!

Tagged with: , ,
Posted in Testing

Byteman – Byte code manipulation tool for Logging, Testing and Fault Injection

Byteman

Byteman is a byte code manipulation tool for fault injection, testing and tracing. The Byteman agent allows to inject the rules into the existing java application with out changing the source code. You can inject the rules during the JVM startup time or into running application with out build and redeploy. We can inject the rules for custom java classes, private methods and the JRE libraries as well. Below are the Byteman use cases.

  • Add logging statements for the legacy application
  • Inject fault scenarios to the application via Junit or TestNG unit test cases

Now, we will see simple java application for which we will add debug statements via Byteman.

Let us write a simple Java application.


package org.smarttechie;

/**
* Class will demonstrate the Byteman
* @author Siva
*
*/
public class BytemanDemonstration {
public static void main(String[] args) {
    System.out.println("With this class we are demonstrating the byteman");
 }
}

Download the latest Byteman distribution.

Write Byteman script to inject the debug statements for the above class.


RULE trace main entry
CLASS BytemanDemonstration
METHOD main
AT ENTRY
IF true
DO traceln("entering into main method")
ENDRULE

RULE trace main exit
CLASS BytemanDemonstration
METHOD main
AT EXIT
IF true
DO traceln("exiting the main method")
ENDRULE

Launch the JVM by passing the Byteman agent and the script file path.

 java -javaagent:${Byteman_Home}\lib\byteman.jar=script:${SCRIPT_FILE_PATH}\logrules.btm <class_name>

After launching the JVM, you will able to see the log messages coming from the script file.


entering into main method
With this class we are demonstrating the byteman
exiting the main method

For further exploration, follow the below links.

https://developer.jboss.org/wiki/ABytemanTutorial#top

https://developer.jboss.org/wiki/BMUnitUsingBytemanWithJUnitOrTestNGFromMavenAndAnt#top

Tagged with: ,
Posted in Java

Memory Analysis – How to obtain Java Heap Dump?

Java Heap Dump

In this article we will see how to obtain the Java Heap Dump to troubleshoot the memory issues like memory leak and high usage of memory. There are different options available to obtain the Heap Dump. The options will vary based on the JVM vendors. In this article I used Oracle JDK8.

Automatically generate the Heap Dump when application throws “OutOfMemoryError”

In this approach, we have to pass the below JVM arguments to get the Heap Dump when application throws “OutOfMemoryError“. The JVM generates the Heap Dump file in the specified file path.

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<path to this heap dump file>

If you have not specified the HeapDumpPath, then the JVM generates the file where the JAVA process is running. The name of the dump file will be like java_pid.hprof.

Some times we might require Heap Dump on demand basis. For example, during the peak load application may become slower and the memory consumption might be more. To troubleshoot the memory consumption, we require Heap Dump.

Manually Generating a Heap Dump

From JDK6, we are having jmap tool to generate the Heap Dump on demand basis. jmap will dump the Java heap in binary HPROF format to a specified file. The instruction is given below.

jmap -dump:format=b,file=<file_name> <pid>
For example, jmap -dump:format=b,file=heap_dump.hprof 4988

In the above example, the 4988 is the java process id to get the heap dump. We can obtain the process id by using jps(Java Virtual Machine Process Status Tool)

There is another GUI utility called jconsole. jconsole can connect to local java process or remote java process. By using MBeans we can get the heap dump.

We can use jvisualvm GUI tool to connect to local or remote JAVA processes. Through jvisualvm also we can generate the heap dump.

All the above said tools are part of JDK. Set the JAVA_HOME and PATH environment variables to access the tools.

In the next article we will see the tools to analyse the heap dumps to detect the memory issues. Till then, stay tune!!! 

 

Tagged with: , , ,
Posted in Java, Performance
DZone

DZone MVB

Java Code Geeks
Java Code Geeks