Sunday, October 29, 2017

How to find max memory, free memory and total memory in Java

As per Javadoc freeMemory is currently available memory which can be allocated to future objects and totalMemory is the total amount of memory in the Java virtual. Since we know that JVM expands heap whenever it needs so if we start our JVM with -Xms10m and -Xmx120m you should expect that initialfreeMemory and totalMemory should be same with starting heap size of JVM as Virtual machine has not been expanded yet and that's the case exactly. even value returned by Runtime.maxMemory() will be close to value of -Xmx though little less. In this article we will see how to get approximate value of inital and maximum heap size, free memory available in JVM and used memory or memory currently occupied by objects in heap.


How to get free Memory in Java

In order to get currently free Memory available for creating object use Runtime.getRuntime().freeMemory() method, this will return size in bytes, which you convert in Mega Bytes for better readability. we will see an example of getting initial heap and free memory in code example section. Calling Garbage collector by either System.gc() or Runtime.gc() may results in slightly higher free memory reclaimed by dead objects.


How to get total Memory in Java

You can use Runtime.getRuntime.totalMemory() to get total memory from JVM which represents current heap size of JVM which is a combination of used memory currently occupied by objects and free memory available for new objects. As per Javadoc value returned by totalMemory() may vary over time depending upon the environment. see the code example for getting total memory in Java in next code example section.


How to get initial Heap Size from Java Program

We specify initial heap space by using -Xms and JVM creates initial heap with this much size. in order to get this size from Java program call Runtime.getRuntime.totalMemory() before creating any object. See code example of getting initial heap size from java program in next section. Apart from –Xms and –Xmx there are lot of other useful JVM Options I have shared on my post 10 useful JVM parameters Java Programmer should know.

How to get maximum Heap Size from Java Program

This is relatively easy as maximum heap space is not going to change over JVM life cycle and call to Runtime.getRuntime.maxMemory() will return value close to -Xmx but keep in mind exact value will be little less than what have you set.


How to get Used Memory in JVM

by using Runtime.getRuntime.totalMemory() and Runtime.getRuntime.freeMemory() we can calculate how much space has been currently occupied by Java object or you say used memory in JVM as show in below code example of getting memory sizes in Java:

Example:


public class MemoryUtil{

       private static final int MegaBytes = 10241024;

       public static void main(String args[]) {

              long freeMemory = Runtime.getRuntime().freeMemory()/MegaBytes;
              long totalMemory = Runtime.getRuntime().totalMemory()/MegaBytes;
              long maxMemory = Runtime.getRuntime().maxMemory()/MegaBytes;

              System.out.println("JVM freeMemory: " + freeMemory);
              System.out.println("JVM totalMemory also equals to initial heap size of JVM : "
                                         + totalMemory);
              System.out.println("JVM maxMemory also equals to maximum heap size of JVM: "
                                         + maxMemory);

              ArrayList objects = new ArrayList();

              for (int i = 0; i < 10000000; i++) {
                     objects.add(("" + 10 * 2710));
              }

              freeMemory = Runtime.getRuntime().freeMemory() / MegaBytes;
              totalMemory = Runtime.getRuntime().totalMemory() / MegaBytes;
              maxMemory = Runtime.getRuntime().maxMemory() / MegaBytes;

              System.out.println("Used Memory in JVM: " + (maxMemory - freeMemory));
              System.out.println("freeMemory in JVM: " + freeMemory);
              System.out.println("totalMemory in JVM shows current size of java heap : "
                                         + totalMemory);
              System.out.println("maxMemory in JVM: " + maxMemory);

       }
}

Output:
JVM freeMemory: 9
JVM totalMemory also equals to initial heap size of JVM : 9
JVM maxMemory also equals to maximum heap size of JVM: 116
Used Memory in JVM: 81
freeMemory in JVM: 35
totalMemory in JVM shows current size of java heap : 108
maxMemory in JVM: 116

How to find if JVM is 32 or 64 bit from Java program.

You can find JVM bit size e.g. 32 bit or 64 bit by using either running java command from the command prompt or by using System.getProperty() from Java program. The question is why do you want to know hardware or platform configuration while writing Java code which is supposed to write once and read anywhere(32 bit, 64 bit etc)? Yes we don't really need to know whether JVM is 32 bit or 64 bit more often but there are many situations when this matters

Check if JVM is 32 or 64 bit from Java program:


  1. Since in 32 bit JVM maximum heap size in Java can not be more than 4GB (theoretically) , if you can get JVM version from a script like running java command you can have different memory configuration for your application. Also, if there is any specific JVM options which only applicable to 64 bit JVM than you can set those.
  2. If your Java application is using native libraries then you certainly want to know whether Java running on the host is 32 bit or 64 bit because native library may have different versions loaded for 32 bit or 64-bit architectures.


I am sure there could me some more practical reasons when you like to find JVM bit size or whether JVM is 64 bit or not

Now let's come to second part how to find if JVM is 32 bit or 64 bit in Java.

How to check if JVM is 32 or 64 bit in host

 As I said earlier there are two different approaches either using Java system property like "sun.arch.data.model" or "os.arch" or by running java command from script and checking its output for certain characters to identify whether JVM is 64 bit or not. let's see example of different ways to find if JVM is 32 bit or 64 bit:


  1. By using System property sun.arch.data.model:


You can find whether your JVM is 32 bit or 64 bit by calling System.getProperty("sun.arch.data.model") at least on Sun's hotspot JVM. I don't expect this to be run on any other Vendor specific JVM but since most of the programmer or project uses Sun's hotspot JVM. this is an handy option. for 32 bit JVM "sun.arch.data.model" will be 32 and for 64 bit JVM this would be 64. here is an example:

System.out.println("JVM Bit size: " + System.getProperty("sun.arch.data.model"));

Output:
JVM Bit size: 32 //JVM is 32 bit
JVM Bit size: amd64 //JVM is 64 bit

2)By using System.getProperty("os.arch")

"os.arch" is another System property which you can use to find whether installed JRE or JVM is 32 bit or 64 bit. by name it sounds that it will return operating system arch but you can still give it a try. Though I haven't tested on all different JVM, I have read that it can indeed return JVM Bitness.If you try this on 64 bit machine and 32 bit JVM combination than please let us know what does it return. here is what it returns in case of 32 bit JVM:

System.out.println("JVM Bit size: " + System.getProperty("os.arch"));

JVM Bit size: x86 //on 32 bit JVM
JVM Bit size: amd64 //on 64 bit JVM

3)java -d64 -version

This is another way of finding whether installed JRE or JVM is 64 bit or not but unfortunately, it
doesn't work with all windows version like Windows XP but it works fine on Windows 7. So you still
use it on Windows7 Machine for finding JVM bitness.

4)java -version

Plain old java -version reveals information about JVM bitness only if installed JRE is 64 bit, in case
of 32 bit JVM it doesn't provide any information related to architecture but in the case of 64 bit JVM it
prints :
C:\>java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)

while in case of 32 bit JVM it will print
C:\> java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)


That’s all on how to find if JVM is 32 bit or 64 bit from Java program and command prompt. As I said its particularly useful if you have a dependency on native libraries which has a different build for 32 bit or 64-bit architecture. Let me know if you have some more ways to find JVM is 64 bit or not, you can also share on which scenario you need to know JVM bitness.




Wednesday, October 18, 2017

Top 5 JSON libraries for a java developer should know


The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.
Actually, there are numerous JSON libraries exists in Java but you don't need to learn all of them, learning just one of them e.g. Jackson should be enough, but, on the other hand, it's worth knowing what are some of the most popular JSON parsing library exists in your disposal. In this article, I am going to share 5 useful JSON libraries which I believe every Java JEE developer should be aware of.
If you are new to JSON, probably heard about it but doesn't know what is JSON there here is a brief introduction of JSON for you. The JSON is an acronym for JavaScript Object Notation, is a lightweight data-interchange format, an alternative to XML, but smaller, faster and easier to parse. Because JSON uses the JavaScript syntax for describing data objects, it is language and platform independent and many parsers and libraries have been developed over the years. You can also read Java XML and JSON to learn more about pros and cons of JSON over XML.

5 Useful JSON libraries in Java

Here is my list of most useful and essential JSON libraries for Java developers. Though I have used them some or other time or other I mostly prefer Jackson because it's a feature rich and I believe in consistency. It doesn't mean those other libraries are not useful, they also have their own strength e.g. Gson is much simpler to use as compared to Jackson and json-simple is a really light-weight library without any third party dependency.
As the purpose of this article is to make you, a Java developer aware of useful JSON library, I leave the decision of choosing the JSON library to yourself. Depending upon your need, you can choose any of them.

Jackson

Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers.
Jackson offers three methods for processing JSON format, each of them having it’s pros and cons:

  1. Streaming API or incremental parsing/generation: reads and writes JSON content as discrete events
  2. Tree model: provides a mutable in-memory tree representation of a JSON document
  3. Data binding: converts JSON to and from POJO’s
If you are only interested in converting Java object to and from JSON string then the third method is most appropriate for you.
Pros of Jackson is that It provides heaps of features, and looks to be a good tool for reading and writing JSON in a variety of ways, but same time its size becomes a disadvantage if your requirement is just to serialize and deserialize Java object to JSON String. 
In order to use Jackson, you can include following maven dependency or manually include jackson-core-2.3.1.jar, jackson-databind-2.3.1.jar, and jackson-annotations-2.3.1.jar in Classpath.

GSON

The second Java JSON binding library we will discuss is Gson, or if you prefer the full name, the google-gson library. Gson is a Java library capable of converting Java objects into their JSON representation and JSON strings to an equivalent Java object without the need for placing Java annotations in your classes.
Some of the salient features of Gson library are:

  1. Provides simple toJson() and fromJson methods to convert Java objects to JSON and vice-versa
  2. Supports arbitrarily complex objects
  3. It has extensive support of Java Generics
  4. Allow custom representation for objects
  5. Allow pre-existing unmodifiable objects to be converted to and from JSON

 json-simple 

The json-simple is one of the simplest JSON library, also lightweight. You can use this library to encode or decode JSON text. It's an open source lightweight library which is flexible and easy to be used by reusing Map and List interfaces from JDK. A good thing about this library that it has no external dependency and both source and binary are JDK 1.2 compatible.

Pros of Json-simple is that it is lightweight, just 12 classes and it provides support for Java IO readers and writers. You can take your decision better if you know about JSON format i.e.g how information is represented there. 
If you are looking for a simple lightweight Java library that reads and writes JSON and supports Streams, json-simple is probably a good match. It does what it says with just 12 classes, and works on legacy (1.4) JREs as well.
In order to use JSON-Simple API, you need to include maven dependency in your project's pom.xml file or alternatively, you can also include following JAR files in your classpath.

Flexjson

Flexjson is another lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. The depth to which an object is serialized can be controlled with Flexjson and thus making it similar to lazy-loading, allowing us to extract only the information we need. This is not the case since we want an entire object to be written to file, but it’s good to know that it can do that.
If you know that you are going to use only a small amount of data in your application and you wish to store or read it to and from JSON format, you should consider using Flexjson or Gson.

JSON-lib

JSON-lib is a Java library, based on the work by Douglas Crockford, capable of transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.
If you are going to use large amounts of data and wish to store or read it to and from JSON format, you should consider using Jackson or JSON-lib.
That's all about some of the useful JSON libraries in Java. You can use these libraries to parse JSON String and generate Java objects or create JSON String from your existing Java objects.
If you are dealing with Web services which return JSON response then these libraries are very important for you. You can choose between them depending upon your need e.g. if you need features and speed then Jackson is probably the best, if you need simplicity then Google Gson looks better to me and if you are concerned about third party dependencies then json-simple or Flexjson can be a good choice.

Sunday, October 15, 2017

Different implementation of RESTFUL webservices

The JAX-RS is a Java specification request (JSR 311 & JSR 339) which standardize development and deployment of RESTful web services using Java and JEE technologies. It provides API in Java Programming language to create web services according to the REST (Representational State Transfer) architectural pattern. Both Restlet and Jersey are two of the most popular implementation of JAX-RS used for developing RESTful web services in Java ecosystem but there are a couple of other implementation also exist e.g. Apache Wink, Apache CXF, and JBoss RESTEasy. In this article, I'll introduce with these RESTful web services framework in Java world. It's not a very detailed post about strength and weakness of each of the framework but will just give you enough to understand them in detail later.

It will also help you to answer the RESTful web service questions like, what is the difference between Restlet, Jersey, and Apache CFX? which one you have used in past, or which one will you choose for your next project and why?

Difference between JAX-RS, Restlet, Jersey, RESTEasy, and Apache CXF Frameworks

Jersey



Jersey RESTful Web Services framework is open source, production quality, a framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) reference Implementation and initially provided by Sun Microsystem.
Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extends the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.

Jersey also has some of the best tooling (IDE) support especially if you are using Netbeans. So you can achieve better productivity from the tooling perspective. There are some challenges with Jersey-Spring integration, especially with AOP.

The latest release of Jersey is 2.26


Restlet


One of the first open source framework for developing RESTful web services in Java. Restlet Framework helps Java developers build better web APIs that follow the REST architecture style. Restlet has a light core but thanks to its pluggable extension, it is also a comprehensive REST framework for Java. It supports all REST concepts (Resource, Representation, Connector, Component, etc.) and is suitable for both client and server Web applications.


It supports major Web standards like HTTP, SMTP, XML, JSON, OData, OAuth, RDF, RSS, WADL, and Atom.

Many extensions are also available to integrate with Servlet, Spring, Jetty, Simple, JAXB, JAX-RS, JiBX, Velocity, FreeMarker, XStream, Jackson, SLF4J, SDC and much more!

Special editions for Android, GWT, GAE, Java SE, Java EE, and OSGi are also available and kept synchronized with an automated porting process.

Another advantage of using Restlet framework is that Restlet based program can run as a standalone Java application. The Restlet also supports Java EE environment with the help of Jetty web container. So this may result in a light-weight implementation and have a unique value that way. There are some challenges or manual work involved in de-marshalling the response into java object. See Restlet in Action to learn more about the Restlet framework.


Apache CXF

The CXF is another free and open source web service framework and a JAX-RS implementation from Apache. CXF helps you to build and develop services using frontend programming APIs like JAX-RS and JAX-WS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS, and JBI.

One of the key difference between Apache CXF and Jersy's JAX-RS implementation is that it is implemented as a CXF filter sitting behind the servlets, while Jersey and RestEasy are, servlet filters.

One more advantage of using ApacheCXF is that it makes it easy to produce both a JAX-RS and JAX-WS (SOAP) endpoint from the exact same data model and service interface at the same time. So if that is something which matters to you, this may be the way to go. CXF had issues with handling SSL and HTTP proxies which seem to have been addressed in recent releases.  You can also read Developing Web Services with Apache CXF and Axis2 to learn more about developing RESTful web services using Apache CXF framework in Java.



RESTEasy

The RESTEasy is another good JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS specification.

RESTEasy may be a good choice if your environment is JBoss oriented e.g. you are using JBoss Application Server, Hibernate and RedHat Middleware, Linux etc. It also provides good integration with EJB 3.0 and SEAM (something to consider if you have a need for that). Also, it has a proprietary caching for URL or query which could be handy for high volume applications.


That's all about the difference between JAX-RS, Restlet, and Jersey in Java. In short, JAX-RS provides the API and these two are the implementation of that API, where Jersey serves as reference implementation but Restlet has got bigger and more matured community around it.

All of these are also mature and production ready frameworks. Chances of going wrong with any of them are quite less. They all have integration capabilities with Spring.  So You can use either Restlet, Jersey or any other framework to develop RESTful web services in Java.


Happy Reading...

Click here to installl Flipkart App

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...