Welcome to NALIN.

It's all about Technology and Programming.

This blog includes information to the trending technologies, hottest programming tutorials and solution to programming problems.

Do you want to contribute to this blog with your knowledge and skills? If yes, then contact us here

Thank you !!!

5 JSON library for Java Developers

Leave a Comment
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.

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.

5 Useful JSON libraries in Java

Here is the 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.


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 maven dependency or manually include jackson-core-x.x.x.jar, jackson-databind-x.x.x.jar, and jackson-annotations-x.x.x.jar in Classpath.


The second Java JSON binding library 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


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 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 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.

Difference between Executor, ExecutorService and Executers class in Java

Leave a Comment
All three classes Executor, ExecutorService, and Executers are part of Java's Executor framework which provides thread pool facilities to Java applications. Since creation and management of Threads are expensive and operating system also imposes restrictions on how many threads an application can spawn, it's a good idea is to use a pool of thread to execute tasks in parallel, instead of creating a new thread every time a request come in. This not only improves the response time of application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread". A thread pool which is created when an application is a startup solves both of these problems. It has ready threads to serve clients when needed and it also has a bound on how many threads to create under load.

From Java 1.5, it was application programmer's responsibility to create and manage such thread pool but from JDK 5 onward Executor framework provides a variety of built-in thread pools in Java e.g. fixed thread pool which contains a fixed number of threads and cached thread pool which can spawn new threads when needed.

The main difference between Executor, ExecutorService, and Executors class is that Executor is the core interface which is an abstraction for parallel execution. It separates task from execution, this is different from java.lang.Thread class which combines both task and its execution. You can read the difference between Thread and Executor to learn more differences between these two key classes of Java.

On the other hand, ExecutorService is an extension of Executor interface and provides a facility for returning a Future object and terminate, or shut down the thread pool. Once the shutdown is called, the thread pool will not accept new task but complete any pending task. It also provides a submit() method which extends Executor.execute() method and returns a Future.

The Future object provides the facility of asynchronous execution, which means you don't need to wait until the execution finishes, you can just submit the task and go around, come back and check if Future object has the result, if execution is completed then it would have result which you can access by using the Future.get() method. Just remember that this method is a blocking method i.e. it will wait until execution finish and the result is available if it's not finished already.

By using the Future object returned by ExecutorService.submit() method, you can also cancel the execution if you are not interested anymore. It provides cancel() method to cancel any pending execution.

Third one Executors is a utility class similar to Collections, which provides factory methods to create different types of thread pools e.g. fixed and cached thread pools. Let's see some more difference between these three classes.

Executor vs ExecutorService vs Executors in Java

As already mentioned, all three classes are part of Java 1.5 Executor framework and it's very important for a Java programmer to learn and understand about these classes to make effective use of different types of thread pools provided by Java. Let's see some key differences between Executor, ExecutorService, and Executors in Java to understand them better:

1) One of the key difference between Executor and ExecutorService interface is that former is a parent interface while ExecutorService extends Executor i.e. it's a sub-interface of Executor.

2) Another important difference between ExecutorService and Executor is that Executor defines execute() method which accepts an object of the Runnable interface, while submit() method can accept objects of both Runnable and Callable interfaces.

3) The third difference between Executor and ExecutorService interface is that execute() method doesn't return any result, its return type is void but submit() method returns the result of computation via a Future object. This is also the key difference between submit() and execute() method, which is one of the frequently asked Java concurrency interview questions.

4) The fourth difference between ExecutorService and Executor interface is that apart from allowing a client to submit a task, ExecutorService also provides methods to control the thread pool e.g. terminate the thread pool by calling the shutDown() method.

5) Executors class provides factory methods to create different kinds of thread pools e.g. newSingleThreadExecutor() creates a thread pool of just one thread, newFixedThreadPool(int numOfThreads) creates a thread pool of fixed number of threads and newCachedThreadPool() creates new threads when needed but reuse the existing threads if they are available.

Reading XML file in java using SAX Parser

Leave a Comment
Reading XML file in java using SAX Parser is little different than reading xml file in Java with DOM parser which we had discussed in last article of this series. This tutorial is can be useful for those who are new to the java world and got the requirement for read an xml file in java in their project or assignment, key feature of java is it provides built in class and object to handle everything which makes our task very easy. Basically this process of handling XML file is known as parsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:

  • Using DOM Parser
  • Using SAX Parser

Read XML file in Java Using SAX Parser Example

In DOM parser we have to follow simple three steps:
  • Parse the XML file
  • Create the java object
  • Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different. 

SAX Parser: It’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls corresponding handler method.

Though there are other ways also to get data from xml file e.g. using XPATH in Java which is a language like SQL and give selective data from xml file.

Sample Example of reading XML File – SAX Parser

Suppose we have this sample XML file bank.xml which contains account details of all accounts in a hypothetical bank:

<?xml version="1.0" encoding="UTF-8"?>
      <Account type="saving">
            <Name>Jack Robinson</Name>
      <Account type="current">
            <Name>Sony Corporation</Name>

  1. Create the SAX parser and parse the XML file: In this step we will take one factory instance from SAXParserFactory to parse the xml  file this factory instance in turns  give us instance of parser using the parse() method will parse the Xml file.
  2. Event Handling: when Sax Parser starts the parsing whenever it founds the start or end tag it will invoke the corresponding event handling method which is public void startElement (…) and public void end Element (...).
  3. Register the events: The class extends the Default Handler class to listen for callback events and we register this handler to sax Parser to notify us for call back event
Let see java code for all these steps. To represent data from our sample xml file we need one java domain object called Account and sample code for implementing SAX parser in Java :

Advantage of SAX parser in Java:

It is faster than DOM parser because it will not load the XML document into the memory .its an event based.

Synchronized block and method in Java

Leave a Comment
Synchronized block and synchronized methods are two ways to use synchronized keyword in Java and implement mutual exclusion on critical section of code. Since Java is mainly used to write multi-threading programs,  which present various kinds of thread related issues like thread-safety, deadlock and race conditions, which plagues into code mainly because of poor understanding of synchronization mechanism provided by Java programming language. Java provides inbuilt synchronized and volatile keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock. Class level lock is one for each class and represented by class literal e.g. Stirng.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java.. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block. In next section we will see an example of both synchronized method and synchronized block to understand this difference better.

Difference between synchronized method vs block in Java

Here are Some more differences between synchronized method and block in Java based upon experience and syntactical rules of synchronized keyword in Java. Though both block and method can be used to provide highest degree of synchronization in Java, use of synchronized block over method is considered as better Java coding practices.

1) One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance. This improves performance drastically because locking is only required one or two times.

2) Synchronized block provide granular control over lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword  or class level lock, if its static synchronized method.

3) Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.

4) In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

Synchronized method vs synchronized block Example in Java

Here is an example of  sample class which shows on which object synchronized method and block are locked and how to use them :

That's all on difference between synchronized method and block in Java. Favoring synchronized block over method is one of the Java best practices to follow as it reduces scope of lock and improves performance. On the other hand using synchronized method are rather easy but it also creates bugs when you mix non static and static synchronized methods, as both of them are locked on different monitors and if you use them to synchronize access of shared resource, it will most likely break.

Double Checked Locking on Singleton Class in Java

Leave a Comment
Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenge they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory models issues in JDK 1.5.

Why you need Double checked Locking of Singleton Class?

One of the common scenario, where a Singleton class breaks its contracts is multi-threading. If you ask a beginner to write code for Singleton design pattern, there is good chance that he will come up with something like below :

private static Singleton _instance;
     public static Singleton getInstance() {
          if (_instance == null) {
               _instance = new Singleton();
     return _instance;
and when you point out that this code will create multiple instances of Singleton class if called by more than one thread parallel, he would probably make this whole getInstance() method synchronized, as shown in our 2nd code example getInstanceTS() method.

Though it’s a thread-safe and solves issue of multiple instance, it's not very efficient. You need to bear cost of synchronization all the time you call this method, while synchronization is only needed on first class, when Singleton instance is created.

This will bring us to double checked locking pattern, where only critical section of code is locked. Programmer call it double checked locking because there are two checks for _instance == null, one without locking and other with locking (inside synchronized) block.

Here is how double checked locking looks like in Java :

public static Singleton getInstanceDC() {
          if (_instance == null) {
               // Single Checked
               synchronized (Singleton.class) {
                    if (_instance == null) {
                    // Double checked
                    _instance = new Singleton();
     return _instance;
On surface this method looks perfect, as you only need to pay price for synchronized block one time, but it still broken, until you make _instance variable volatile.

Without volatile modifier it's possible for another thread in Java to see half initialized state of _instance variable, but with volatile variable guaranteeing happens-before relationship, all the write will happen on volatile _instance before any read of _instance variable.

This was not the case prior to Java 5, and that's why double checked locking was broken before. Now, with happens-before guarantee, you can safely assume that this will work.

That's all about double checked locking of Singleton class in Java.

Creating a memory leak with Java.

Leave a Comment
Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in Java:
  1. The application creates a long-running thread (or use a thread pool to leak even faster).
  2. The thread loads a class via an (optionally custom) ClassLoader.
  3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.
  4. The thread clears all references to the custom class or the ClassLoader it was loaded from.
  5. Repeat.

This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded.

(It was worse in many JVM implementations, especially prior to Java 7, because Classes and ClassLoaders were allocated straight into permgen and were never GC'd at all. However, regardless of how the JVM handles class unloading, a ThreadLocal will still prevent a Class object from being reclaimed.)

A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications that happen to use ThreadLocals in any way. (Since the application container uses Threads as described, and each time you redeploy the application a new ClassLoader is used.)

Factory Design Pattern in Java

Leave a Comment
Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of factory pattern in Java is BorderFactory Class of Swing API.

What is static factory method or factory design pattern?

Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. In GOF pattern list Factory pattern is listed as Creation design pattern. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.

Example of static factory method in JDK

Best Example of Factory method design pattern is valueOf() method which is there in String and wrapper classes like Integer and Boolean and used for type conversion i.e. from converting String to Integer or String to double in java..

Some more examples of factory method design pattern from JDK is :

  • valueOf() method which returns object created by factory equivalent to value of parameter passed.
  • getInstance() method which creates instance of Singleton class.
  • newInstance() method which is used to create and return new instance from factory method every time called.
  • getType() and newType() equivalent of getInstance() and newInstance() factory method but used when factory method resides in separate class.

Problem which is solved by Factory method Pattern in Java

Whenever we talk about object oriented language it will based upon some concept like abstraction, polymorphism etc and on that encapsulation and delegation are important concept any design will be called good if task are delegated to different object and some kind of encapsulation is there.

Some time our application or framework will not know that what kind of object it has to create at run-time it knows only the interface or abstract class and as we know we can not create object of interface or abstract class so main problem is frame work knows when it has to create but don’t know what kind of object.

Whenever we create object using new() we violate principle of programming for interface rather than implementation which eventually result in inflexible code and difficult to change in maintenance. By using Factory design pattern in Java we get rid of this problem.

Another problem we can face is class needs to contain objects of other classes or class hierarchies within it; this can be very easily achieved by just using the new keyword and the class constructor. The problem with this approach is that it is a very hard coded approach to create objects as this creates dependency between the two classes.

So factory pattern solve this problem very easily by model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate, Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. The factory methods are typically implemented as virtual methods, so this pattern is also referred to as the “Virtual Constructor”. These methods create the objects of the products or target classes.

When to use Factory design pattern in Java

  • Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework.        
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
  • Factory method is used when Products don't need to know how they are created.
  • We  can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided

Code Example of Factory Design Pattern in Java

Let’s see an example of how factory pattern is implemented in Code.We have requirement to create multiple currency e.g. NRS, SGD, USD and code should be extensible to accommodate new Currency as well. Here we have made Currency as interface and all currency would be concrete implementation of Currency interface. Factory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible.

Here is complete code example of Factory pattern in Java:

interface Currency {
       String getSymbol();

// Concrete Rupee Class code
class Rupee implements Currency {
       public String getSymbol() {
              return "Rs";

// Concrete SGD class Code
class SGDDollar implements Currency {
       public String getSymbol() {
              return "SGD";

// Concrete US Dollar code
class USDollar implements Currency {
       public String getSymbol() {
              return "USD";

// Factroy Class code
class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("Nepal")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
       throw new IllegalArgumentException("No such currency");

// Factory client code
public class Factory {
       public static void main(String args[]) {
              String country = args[0];
              Currency rupee = CurrencyFactory.createCurrency(country);

Advantage of Factory method Pattern in Java:

Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In following are main advantages of using Factory pattern in Java:

  • Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?

    E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?
  • Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.
  • Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.
  • Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.

Some more advantages of factory method design pattern is:

  • Static factory method used in factory design pattern enforces use of Interface than implementation which itself a good practice. for example:

    Map synchronizedMap = Collections.synchronizedMap(new HashMap());
  • Since static factory method have return type as Interface, it allows you to replace implementation with better performance version in newer release.
  • Another advantage of static factory method pattern is that they can cache frequently used object and eliminate duplicate object creation. Boolean.valueOf() method is good example which caches true and false boolean value.
  • Factory method pattern is also recommended by Joshua Bloch in Effective Java.
  • Factory method pattern offers alternative way of creating object.
  • Factory pattern can also be used to hide information related to creation of object.