Friday, April 17, 2015

Java Management Extensions - JMX

Java Management Extensions is a way to create management interface to Java applications. In brief, adding extra wrapper (MBean) to your application with a name (ObjectName) and register it on management server MBeanServer, so that it can be accessed/managed externally. JMX allows the developers to integrate the application by assigning management attributes/operations.

Instrumentation

To use JMX, we need to instrument the Java classes (or resources). The instrumented objects are called MBeans. MBeans are nothing but POJOs which adhere to JMX specifications.

MBeanServer

MBeanServer is the very core component of the JMX. MBeanServer is the JMX agent which hosts the MBeans on it and make them available for the remote applications. The MBeanServer need not to know how the MBeans are implemented and vice-versa. 

Accessing MBeans

MBeans running on MBeanServer can be accessed using Connectors, typically called as JMX Connectors, using JMX Service URL. The main intention of the connector is to provide an interface to establish communication between JMX agent and the application which is trying to access the MBean. There are various connectors available, but it always recommended use a standard RMIConnector.  

JMX Service URL

The URL is used to connect to MBean agent and locate MBeans to acess. There are two types of URLs depending on how the JMX is implemented on broker.
  • Static URL: As the name suggests, Static URL will create constant identity for MBeans irrespective of when and how broker is started, stopped etc. This uses RMI Connector.
  • Dynamic URL: Dynamic URL keeps changes for each time when the broker is started/re-started.

URL looks like

service:jmx:rmi://hostname:port/<urlpath>
The explanation goes here
  • service:jmx:rmi is constant
  • hostname:port is the name and port of the broker host where the MBean agent resides (Ideally, where the application is running)
  • urlpath is depends on where Service URL is static or dynamic
    • Static URL looks like : /jndi/rmi://hostname[:rmiPort]/jndiname
    • Dynamic URL looks like : /stub/serialnumber-with-base64encoded

Static JMX Service URL

Static URL contains the details of the RMI registry like hostname, port number and the connector name 
/jndi/rmi://hostname[:rmiPort]/connectorname 
  • hostname[:rmiPort] : RMI host and post number to locale JMX agent. By default, RMI port will be 1099 (if not specified). 
  • connectorname specifies the name which needs to be look-up in the RMI registry.
See the post, how to implement JMX MBean using Spring

Dynamic JMX Service URL

The URL consists of the serialized JMX object with Base 64 encoded value. See an example below
/stub/rO0ABdmVyLlJlpIDJyGvQkwAAAARod97VdgAEAeA==
We will see how to create JMX MBeans using dynamic URLs and how to access.

Happy Learning!!!!

Thursday, April 9, 2015

String and String Constant Pool

String and String Constant Pool

String is the most known Immutable Class in Java. Immutable means, the contents can't be changed once initialized. That's the reason, we keep hearing that to use StringBuffer for string modifications instead of String. When we modify the contents of String (see samples below) will create a new copy of String and assigns the reference. String Constant Pool is a pool of Strings maintained by JVM for storing the strings created and its references. See code below to know what happens when a string constant is created.
      String string1 = "veeresh"; 
      String string2 = "veeresh"; 
      string1.concat(string2);

Points to be noted

  • A constant veeresh will be created and reference will be assigned to string1
  • When trying to create one more constant with the same value, JVM will pick it up from String constant pool and get the reference and assigns to string2. So, string1 and string2 are referring same.
  • If we perform an operation on a string - like concat in the above code, a new string will be created with value veereshveeresh. But there is no assignment, hence we can't acess it in our program but it will present in String constant pool

More about String Constant Pool

No new string will be created only if it's a constant. If we create a string using new keyword, then a new string reference will be created. See below
        String string1 = "veeresh";
        String string2 = new String("veeresh");
        String string3 = "hi";
        String string4 = string3.concat(" "+string2);
In above code
  • On line 1, a new constant veeresh will be created in String Constant Pool and reference is assigned to string1
  • On line 2, a new Object whose value is veeresh will be created - not taken from string constant pool as we used new keyword.
  • On line 3, a new constant hi will be created in String Constant Pool and reference is assigned to string3
  • On line 4, a new constant Space (" ") will be created and then " veeresh" (Space suffixed with veeresh) created and finally "hi veeresh" will be created in String Constant Pool and assigned to string4 as reference. So, total 3 strings will be created here (Space, " veeresh" and "hi veeresh").

Why Only for String

Only String class  has Constant Pool, Other types like Integer, Char, Number etc doesn't have Constant pool even though they are Immutable. The important reason so far i got are Security and Frequency of Usage.
  • String is the most frequent used like System.out.println and arguments that we pass most of the methods and even main method accepts an array of Strings. So, JVM referes to String Constant Pool every time when a new string created in order to reduce the number of references.
  • I am not really sure what security we get but i found on web as this is one of the reasons.
I am in search of other reasons for why only String. 

To Summarize

  • Every time, when a string constant is created, JVM checks String Constant Pool whether exists. If exists, the same reference will be returned otherwise creates it
  • In order to create new string without taking from Constant Pool, use new keyword
  • Any operation on string will result in new object (or constant)
  • If we want to create strings for doing some modifications, use StringBuffer instead of String
Help me with more details if you know anything else. Happy Learning!!!

Wednesday, April 8, 2015

Debugging MQ Java Client Applications

I find it very difficult to debug the Java client application written for MQ. Most of the error messages are self explanatory but some of the error messages are difficult to diagnose and find the cause. Enable tracing would really help to identify the root of the problem. In this post, we will see how to enable tracing on Java applications.

MQ Trace

Simple MQ Trace enabling can be done by adding a JVM parameter like this
java -Dcom.ibm.mq.commonservices=trace.properties ...
Create trace.properties with the following attributes
Diagnostics.MQ=enabled
Diagnostics.Java=explorer,wmqjavaclasses,all
Diagnostics.Java.Trace.Detail=high
Diagnostics.Java.Trace.Destination.File=enabled
Diagnostics.Java.Trace.Destination.Console=disabled
Diagnostics.Java.Trace.Destination.Pathname=/tmp/trace
Diagnostics.Java.FFDC.Destination.Pathname=/tmp/FFDC
Diagnostics.Java.Errors.Destination.Filename=/tmp/errors/AMQJERR.LOG

Points to be noted

  • Add libraries of IBM JRE (From the directory $JRE_HOME/lib) to CLASSPATH
  • Create the directories /tmp/FFDC, /tmp/trace and /tmp/errors
  • Add read permission to trace.properties
  • Keep an eye on the log file size and make sure to disable logging when not required. Otherwise, it will keep filling the disk space. (Logs size will become some gigs in few hours easily)
One you start the Java Client, it will start printing the trace into the mentioned files. If you want to disable the tracing, make the Diagnostics.MQ property value to disabled so that trace will be stopped. 

JSSE Debug

In case of secure connection with MQ, if you want to enable debug for JSSE, then you can use the JVM parameter java.net.debug with different values
-Djavax.net.debug=true
This prints full trace of JSSE, this can be limited to only handshake by changing the value of the parameter to ssl:handshake
-Djavax.net.debug=ssl:handshake
This prints only the trace related to handshake, all other trace will be simply ignored.

Happy Learning!!!!

Saturday, April 4, 2015

Concurrency and Persistency using Chronicle Map

If you want a persistent, less heap and concurrent maps, then Chronicle Hash Map is the best one to use. Chronicle Map also helps in sharing the data between the JVMs. Earlier version of ChronicleMap is SharedHashMap.

Download

Add the following repository to your pom.xml with the following dependency.
<!-- Repository. Add inside repositories -->
<repository>
    <id>Snapshot Repository</id>
    <name>Snapshot Repository</name>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

<!-- Add the following dependency -->
<dependency>
  <groupId>net.openhft</groupId>
  <artifactId>chronicle-map</artifactId>
  <version>2.1.4</version>
</dependency>

Points to be noted

There are few points to be noted about a ChronicleMap.
  • It stores the data onto a file for persistency.
  • In order to implement, the object (which has to be stored) must implement Serializable/Externalizable
  • Two programs can share the same file (Used while creating the map) to share the same data across JVMs.
  • Replication can be done using Chronicle Map using TCP/IP. (not detailed in the current post).
  • No need to depend on JVM Heap Memory as the data is store Off-Heap (on a file).
  • And the last important point is, the performance of the Map is purely dependent on how the Operating System allocates the memory to the file.
If we clearly observe, all these advantages or features are because of storing a data off-heap using a file.

How to create

ChronicleMap is created using ChronicleMapBuilder. See the sample code for creating the map.
        Map<Integer,String> map = ChronicleMapBuilder.of(Integer.class,
                String.class).create();
If you want to persist the data to a file. Use like this
        File f = new File("/tmp/file.map");
        Map<Integer, String> map = ChronicleMapBuilder.of(Integer.class,
                String.class).
                createPersistedTo(f);
Here, we are creating map and persisting to a file /tmp/file.map. As its storing the data onto a file, we can limit the size of the Map by specific number of entries it can store. See below
        Map<Integer,String> map = ChronicleMapBuilder.of(Integer.class,
                String.class).
                entries(2000).
                createPersistedTo(new File("/tmp/file.map"));
There is a difference between Concurrent Map and Chronicle Map in size. It can't be re-sized once we fix the entries size as re-sizing is a costly operation on Map.

ChronicleMap Interface

There are few specials methods which are provided by ChronicleMap. See below

  • V getUsing(K key, V value); getUsing is same as get(key) but getUsing will return the value in value parameter without creating a new object whereas get will create a new object for returning the value with key.
  • V acquireUsing(K key, V value); acquireUsing is again same as getUsing but if there is no value defined with key, it will insert a new entry with key and returns the same value.

ChronicleMap can read and write the data from/to a JSON object. The following methods can be used to do so

  • void getAll(File toFile) throws IOException; To read map from the file which was created by another ChronicleMap using JSON format.
  • void putAll(File fromFile) throws IOException; To dump the entire map into a file using a JSON format.
  • void close(); As the data is stored off-heap, its recommended to close the map to release the heap data and persist the data.

All other methods are same as Map as it implements java.util.Map. Explore more on ChronicleMap

Happy Learning!!!!