TechDoko: Java

Hot

Post Top Ad

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Difference between Executor, ExecutorService and Executers class in Java

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

Reading XML file in java using SAX Parser

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:

     
            1001
            Jack Robinson
            10000
     
     
            1002
            Sony Corporation
            1000000
     

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

Synchronized block and method in Java

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

Double Checked Locking on Singleton Class in Java

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

Creating a memory leak with Java.

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.)
Read More

Difference between Setter vs Constructor Injection in Spring.

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article.

Difference between Setter and Constructor Injection in Spring framework

Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn't support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.

2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it's not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.

3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.


4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.
Read More

Send HTTP request GET/POST in Java

HTTP stands for Hypertext Transfer Protocol. It is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. A web browser sends HTTP request to an application that resides on the remote host computer and the application responses to that request. HTTP request can be of different type.

In this post I am going to give an example of HTTP GET/POST request using Java.

1. Java HttpURLConnection example

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {
 private final String USER_AGENT = "Mozilla/5.0";
 public static void main(String[] args) throws Exception {
  HttpURLConnectionExample http = new HttpURLConnectionExample();
  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();
  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();
 }

  // HTTP GET request
  private void sendGet() throws Exception {
  String url = "http://www.google.com/search?q=nepal";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

  // optional default is GET
  con.setRequestMethod("GET");

  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);
  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  //print result
  System.out.println(response.toString());
 }


 // HTTP POST request
 private void sendPost() throws Exception {
  String url = "https://selfsolve.apple.com/wcResults.do";
  URL obj = new URL(url);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

  //add reuqest header
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

  String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + urlParameters);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

    //print result
  System.out.println(response.toString());

 }
}

2. Apache HttpClient

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientExample {
 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {
  HttpClientExample http = new HttpClientExample();
  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();
  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();
 }

 // HTTP GET request
 private void sendGet() throws Exception {
  String url = "http://www.google.com/search?q=developer";

  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet(url);

  // add request header
  request.addHeader("User-Agent", USER_AGENT);

  HttpResponse response = client.execute(request);
  System.out.println("\nSending 'GET' request to URL :" + url);
  System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(new
InputStreamReader( response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }
  System.out.println(result.toString());
 }

 // HTTP POST request
 private void sendPost() throws Exception {
  String url ="https://selfsolve.apple.com/wcResults.do";
  HttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost(url);

  // add header
  post.setHeader("User-Agent", USER_AGENT);
  List urlParameters = new ArrayList();
  urlParameters.add(new BasicNameValuePair("sn","C02G8416DRJM"));
  urlParameters.add(new BasicNameValuePair("cn", ""));
  urlParameters.add(new BasicNameValuePair("locale",""));
  urlParameters.add(new BasicNameValuePair("caller",""));
  urlParameters.add(new BasicNameValuePair("num","12345"));

  post.setEntity(new UrlEncodedFormEntity(urlParameters));

  HttpResponse response = client.execute(post);
  System.out.println("\nSending 'POST' request to URL: " + url);
  System.out.println("Post parameters : " +post.getEntity());
  System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }
  System.out.println(result.toString());
 }
}
Read More

Sending Email using Java

To send an email using Java Application, you need JavaMail API and Java Activation Framework (JAF). You can download the latest version of JavaMail API from Java's website. Click here to open the Java's website. For the download of latest version of JAF you can click here.

Just download and extract those files in your machine. You will find number of files but you only need mail.jar and activation.jar. Just add those files in your project CLASSPATH.

Send a Simple E-mail

Before sending a simple email, first you have to connect your machine with the internet. Here is a sample code for sending a simple email. Create a project in any IDE (I am using Eclipse) and create a java file named as SendEmail.java and paste the below code.

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {
   public static void main(String [] args) { 
      // Recipient's email ID needs to be mentioned.
      String to = "abc@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "xyz@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new
         InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");

      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Now just run this file as Java Application and your email will be sent to the recipient's email address.

If you have multiple recipient for sending the email, then you can specify the multiple email id as follows:

void addRecipients(Message.RecipientType type, Address[] addresses)throws MessagingException

Here, type can be set to TO, CC or BCC. CC represents Carbon Copy and BCC represents Black Carbon Copy. Example, Message.RecipientType.TO and addresses is the array of email ID. You have to use InternetAddress() method for specifying email IDs.

User Authentication

If sending email fails due to required authentication to the mail server then you can provide the user authentication by following ways and the rest of the process is as it is.


properties.setProperty("mail.user", "myuser");
properties.setProperty("mail.password", "mypwd");
Read More

Difference between AWT and Swing?

AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.

Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, check-boxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "plug-gable look and feel" that can make it look more or less like how the native windows and widgets would look).

These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:

AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those tool kits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.

Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.

Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.

Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.
Read More

Difference between JSP and Servlets

Before I talk about the difference between JSP and Servlets, first of all I would like to talk about what is JSP and what is Servlets. JSP is Java Server Page which is the extension of Servlets. I will discuss about the Servlets in next paragraph. JSP simplify the delivery of dynamic Web content. Web applications programmer can create dynamic content by using the predefined components available in JSP and by interacting with components using server-side scripting.

Now, as talking about Servlets, they are the simply Java programs and they are also capable of creating dynamic web content. Servlets execute on the server side of a Web connection and they also extends the Web server's functionality; i.e. they extends the capabilities of servers that host applications. Those applications can be accessed via a request-response programming model.

Finally, I would like to present a short differences between JSP and Servlets. JSP is a webpage scripting language that can generate dynamic content where as Servlets are the Java programs that are already compiled which also create dynamic web content. JSP executes or run slower compared to Servlets as it takes time to convert JSP to Servlets but unlike JSP, Servlets run faster. Coding is easier in JSP but it's not so easy to write code in Servlets. In Model View Controller (MVC) pattern, JSP act as a view where as Servlets act as a controller. However, JSP is preferred if there is not much processing of data is required but in this case Servlets can handel much huge request/response processing and manipulation. JSP also has advantages, one of the best advantage of JSP over Servlets is that we can define custom tags which can be use to call Java Beans. But there is no concept of custom tags in Servlets. By running JavaScript in client side, we can achieve functionality of JSP but there is no such methods for Servelts.
Read More

Java Virtual Machine (JVM)

Java is a high level programming language. A program written in high level language cannot be run on any machine directly. First, it needs to be translated into that particular machine language. The javac compiler does this thing, it takes java program (.java file containing source code) and translates it into machine code (referred as byte code or .class file).

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code. This makes it easier for compiler as it has to generate byte code for JVM rather than different machine code for each type of machine. JVM executes the byte code generated by compiler and produce output. JVM is the one that makes java platform independent.

So, now we understood that the primary function of JVM is to execute the byte code produced by compiler. Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. Which means that the byte code generated on Windows can be run on Mac OS and vice versa. That is why we call java as platform independent language. The same thing can be seen in the diagram below:
The Java Virtual machine (JVM) is the virtual machine that runs on actual machine (your computer) and executes Java byte code. The JVM doesn’t understand Java source code, that’s why we need to have javac compiler that compiles *.java files to obtain *.class files that contain the byte codes understood by the JVM. JVM makes java portable (write once, run anywhere). Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems.
JVM Architecture

JVM Architecture
Class Loader: The class loader reads the .class file and save the byte code in the method area.

Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class level information of each .class file.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each .class file.

Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.

PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed. Since instructions are executed by threads, each thread has a separate PC register.

Native Method stack: A native method can access the runtime data areas of the virtual machine.

Native Method interface: It enables java code to call or be called by native applications. Native applications are programs that are specific to the hardware and OS of a system.

Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed by garbage collection for memory management.

JVM Vs JRE Vs JDK

JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger. Which means you can run the code in JRE but you can’t develop and compile the code in JRE.

JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.
JRE
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.
JDK
Read More

Java Design Patterns

Design Patterns are very popular among software developers. A design pattern is a well described solution to a common software problem. Some of the benefits of using design patterns are:

1. Design Patterns are already defined and provides industry standard approach to solve a recurring problem, so it saves time if we sensibly use the design pattern. There are many java design patterns that we can use in our java based projects.
2. Using design patterns promotes reusability that leads to more robust and highly maintainable code. It helps in reducing total cost of ownership (TCO) of the software product.
3. Since design patterns are already defined, it makes our code easy to understand and debug. It leads to faster development and new members of team understand it easily.
Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns.

1. Creational Design Patterns
a. Singleton Pattern
b. Factory Pattern
c. Abstract Factory Pattern
d. Builder Pattern
e. Prototype Pattern

2. Structural Design Patterns
a. Adapter Pattern
b. Composite Pattern
c. Proxy Pattern
d. Flyweight Pattern
e. Facade Pattern
f. Bridge Pattern
g. Decorator Pattern

3. Behavioral Design Patterns
a. Template Method Pattern
b. Mediator Pattern
c. Chain of Responsibility Pattern
d. Observer Pattern
e. Strategy Pattern
f. Command Pattern
g. State Pattern
h. Visitor Pattern
i. Interpreter Pattern
j. Iterator Pattern
k. Memento Pattern

Creational Design Patterns

Creational design patterns provide solution to instantiate a object in the best possible way for specific situations.
a. Singleton Pattern
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. It seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic among developers.

b. Factory Pattern
Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern take out the responsibility of instantiation of a class from client program to the factory class. We can apply Singleton pattern on Factory class or make the factory method static.

c. Abstract Factory Pattern
Abstract Factory pattern is similar to Factory pattern and it’s factory of factories. If you are familiar with factory design pattern in java, you will notice that we have a single Factory class that returns the different sub-classes based on the input provided and factory class uses if-else or switch statement to achieve this. In Abstract Factory pattern, we get rid of if-else block and have a factory class for each sub-class and then an Abstract Factory class that will return the sub-class based on the input factory class.

d. Builder Pattern
This pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

e. Prototype Pattern
Prototype pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. This pattern uses java cloning to copy the object. Prototype design pattern mandates that the Object which you are copying should provide the copying feature. It should not be done by any other class. However whether to use shallow or deep copy of the Object properties depends on the requirements and its a design decision.

Structural Design Patterns

Structural patterns provide different ways to create a class structure, for example using inheritance and composition to create a large object from small objects.

a. Adapter Pattern
Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter. As a real life example, we can think of a mobile charger as an adapter because mobile battery needs 3 volts to charge but the normal socket produces either 120V (US) or 240V (Nepal). So the mobile charger works as an adapter between mobile charging socket and the wall socket.

b. Composite Pattern
Composite pattern is one of the Structural design pattern and is used when we have to represent a part-whole hierarchy. When we need to create a structure in a way that the objects in the structure has to be treated the same way, we can apply composite design pattern. Lets understand it with a real life example – A diagram is a structure that consists of Objects such as Circle, Lines, Triangle etc and when we fill the drawing with color (say Red), the same color also gets applied to the Objects in the drawing. Here drawing is made up of different parts and they all have same operations.

c. Proxy Pattern
Proxy pattern intent is to “Provide a surrogate or placeholder for another object to control access to it”. The definition itself is very clear and proxy pattern is used when we want to provide controlled access of a functionality. Let’s say we have a class that can run some command on the system. Now if we are using it, its fine but if we want to give this program to a client application, it can have severe issues because client program can issue command to delete some system files or change some settings that you don’t want.

d. Flyweight Pattern
Flyweight design pattern is used when we need to create a lot of Objects of a class. Since every object consumes memory space that can be crucial for low memory devices, such as mobile devices or embedded systems, flyweight design pattern can be applied to reduce the load on memory by sharing objects. String Pool implementation in java is one of the best example of Flyweight pattern implementation.

e. Facade Pattern
Facade Pattern is used to help client applications to easily interact with the system. Suppose we have an application with set of interfaces to use MySql/Oracle database and to generate different types of reports, such as HTML report, PDF report etc. So we will have different set of interfaces to work with different types of database. Now a client application can use these interfaces to get the required database connection and generate reports. But when the complexity increases or the interface behavior names are confusing, client application will find it difficult to manage it. So we can apply Facade pattern here and provide a wrapper interface on top of the existing interface to help client application.

f. Bridge Pattern
When we have interface hierarchies in both interfaces as well as implementations, then bridge design pattern is used to decouple the interfaces from implementation and hiding the implementation details from the client programs. Like Adapter pattern, its one of the Structural design pattern. The implementation of bridge design pattern follows the notion to prefer Composition over inheritance.

g. Decorator Pattern
Decorator design pattern is used to modify the functionality of an object at run-time. At the same time other instances of the same class will not be affected by this, so individual object gets the modified behavior. Decorator design pattern is one of the structural design pattern (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses abstract classes or interface with composition to implement. We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can’t add any new functionality of remove any existing behavior at run-time – this is when Decorator pattern comes into picture.

Behavioral Design Patterns

Behavioral patterns provide solution for the better interaction between objects and how to provide lose coupling and flexibility to extend easily.

a. Template Method Pattern
Template Method is a behavioral design pattern and it’s used to create a method stub and deferring some of the steps of implementation to the sub-classes. Template method defines the steps to execute an algorithm and it can provide default implementation that might be common for all or some of the sub-classes. Suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that the we can’t change the order of execution because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.

b. Mediator Pattern
Mediator design pattern is used to provide a centralized communication medium between different objects in a system. Mediator design pattern is very helpful in an enterprise application where multiple objects are interacting with each other. If the objects interact with each other directly, the system components are tightly-coupled with each other that makes maintainability cost higher and not flexible to extend easily. Mediator pattern focuses on provide a mediator between objects for communication and help in implementing lose-coupling between objects. Air traffic controller is a great example of mediator pattern where the airport control room works as a mediator for communication between different flights. Mediator works as a router between objects and it can have it’s own logic to provide way of communication.

c. Chain of Responsibility Pattern
Chain of responsibility pattern is used to achieve lose coupling in software design where a request from client is passed to a chain of objects to process them. Then the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not. We know that we can have multiple catch blocks in a try-catch block code. Here every catch block is kind of a processor to process that particular exception. So when any exception occurs in the try block, its send to the first catch block to process. If the catch block is not able to process it, it forwards the request to next object in chain i.e next catch block. If even the last catch block is not able to process it, the exception is thrown outside of the chain to the calling program. ATM dispense machine logic can be implemented using Chain of Responsibility Pattern.

d. Observer Pattern
Observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watch on the state of another object are called Observer and the object that is being watched is called Subject. Java provides inbuilt platform for implementing Observer pattern through java.util.Observable class and java.util.Observer interface. However it’s not widely used because the implementation is really simple and most of the times we don’t want to end up extending a class just for implementing Observer pattern as java doesn’t provide multiple inheritance in classes. Java Message Service (JMS) uses Observer pattern along with Mediator pattern to allow applications to subscribe and publish data to other applications.

e. Strategy Pattern
Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at run-time. Strategy pattern is also known as Policy Pattern. We defines multiple algorithms and let client application pass the algorithm to be used as a parameter. One of the best example of this pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

f. Command Pattern
Command Pattern is used to implement lose coupling in a request-response model. In command pattern, the request is send to the invoker and invoker pass it to the encapsulated command object. Command object passes the request to the appropriate method of Receiver to perform the specific action. Let’s say we want to provide a File System utility with methods to open, write and close file and it should support multiple operating systems such as Windows and Unix. To implement our File System utility, first of all we need to create the receiver classes that will actually do all the work. Since we code in terms of java interfaces, we can have FileSystemReceiver interface and it’s implementation classes for different operating system flavors such as Windows, Unix, Solaris etc.

g. State Pattern
State design pattern is used when an Object change it’s behavior based on it’s internal state. If we have to change the behavior of an object based on it’s state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.

h. Visitor Pattern
Visitor pattern is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class. For example, think of a Shopping cart where we can add different type of items (Elements), when we click on checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using visitor pattern. Let’s implement this in our example of visitor pattern.

i. Interpreter Pattern
This pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar. The best example of this pattern is java compiler that interprets the java source code into byte code that is understandable by JVM. Google Translator is also an example of interpreter pattern where the input can be in any language and we can get the output interpreted in another language.

j. Iterator Pattern
Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way to traverse through a group of Objects. Iterator pattern is widely used in Java Collection Framework where Iterator interface provides methods for traversing through a collection. Iterator pattern is not only about traversing through a collection, we can provide different kind of iterators based on our requirements. Iterator pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods.

k. Memento Pattern
Memento design pattern is used when we want to save the state of an object so that we can restore later on. Memento pattern is used to implement this in such a way that the saved state data of the object is not accessible outside of the object, this protects the integrity of saved state data. Memento pattern is implemented with two objects – Originator and Caretaker. Originator is the object whose state needs to be saved and restored and it uses an inner class to save the state of Object. The inner class is called Memento and its private, so that it can’t be accessed from other objects.

That’s all for different design patterns in java.
Read More

Introduction to Java programming

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James Gosling and Patrick Naughton. It is a simple programming language.  Writing, compiling and debugging a program is easy in java.  It helps to create modular programs and reusable code.

Java terminology

1. Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. Phases are as follows: we write the program, then we compile the program and at last we run the program.

a. Writing of the program is of course done by java programmer like you and me.
b. Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output.
c. In third phase, JVM executes the bytecode generated by compiler. This is called program run phase.

Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

2. bytecode
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a .class file by compiler.

3. Java Development Kit(JDK)
While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name suggests this is complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer.

These are the basic java terms that confuses beginners in java. For complete java glossary refer this link: https://docs.oracle.com/javase/tutorial/information/glossary.html

Main Features of JAVA

1. Java is a platform independent language
Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-versa. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

2. Java is an Object Oriented language
Object oriented programming is a way of organizing programs as collection of objects, each of which represents an instance of a class.

Four main concepts of Object Oriented programming are:
a. Abstraction
b. Encapsulation
c. Inheritance
d. Polymorphism

3. Simple
Java is considered as one of simple language because it does not have complex features like Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.

4. Robust Language
Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.

5. Secure
We don’t have pointers and we cannot access out of bound arrays (you get ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.

6. Java is distributed
Using java programming language we can create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In simple words: The java programs can be distributed on more than one systems that are connected to each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a remote JVM.

7. Multithreading
Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU.

8. Portable
As discussed above, java code that is written on one machine can run on another machine. The platform independent byte code can be carried to any platform for execution that makes java code portable.
Read More

Top 20 Libraries and APIs for Java Developer

There is no point in re-inventing the wheels. 
One of the traits of a good and experienced Java developer is the extensive knowledge of API, including JDK and third-party libraries. This article is going to share some of the most useful and essential libraries and API, a Java developer should be familiar with which includes frameworks e.g. Spring and Hibernate because they are pretty well known and have specific features. In addition to this, the article also includes useful libraries for day to day stuff e.g. logging libraries like Log4j, JSON parsing libraries like Jackson, and unit testing API e.g. JUnit and Mockito. If you need to use them in your project then you can either include JARs of these libraries in your project's classpath to start using them or you can use Maven or Gradle for dependency management.

When you use Maven or Gradle for dependency management, then it will automatically download these libraries, including the libraries they depend, known as the transitive dependency. For example, if you download Spring Framework then it will also download all other JARs on which Spring is dependent e.g. Log4j etc. You might not realize but having the right version of dependent JARs is a big headache. If you have wrong versions of the JAR then you will get ClassNotFoundException or NoClassDefFoundError, or UnsupportedClassVersionError.

Here is the collection of some of the useful third-party libraries Java developers can use in their application to do a lot of useful tasks. In order to use these libraries, Java developer should also be familiar with that.

1. Logging libraries
Logging libraries are very common because you need them in every project. They are the most important thing for server-side application because logs are only placed where you can see what's going on your application. Even though JDK ships with its own logging library, there are many better alternatives are available e.g. Log4j, SLF4j, and LogBack.
2. JSON parsing libraries
In today's world of web services and internet of things (IoT), JSON has become the go-to protocol to carry information from client to server. They have replaced the XML as the most preferred way to transfer information in a platform-independent way. Unfortunately JDK doesn't have a JSON library yet but fortunately, there are many good third-party libraries which allows you to both parse and create JSON messages e.g. Jackson and Gson.

3. Unit testing libraries
Unit testing is the single most important thing which separates an average developer from a good developer. Programmers often are given excuses for not writing unit tests but the most common excuse for avoiding unit testing is lack of experience and knowledge of popular unit testing library e.g. JUnit, Mockito, and PowerMock.
4. General purpose libraries
There is a couple of very good general purpose, third-party library available to Java developer e.g. Apache Commons and Google Guava. These libraries always simplify a lot of tasks.
5. Http libraries
JDK 9 brought support for HTTP 2.0 and HTTP connection can be made easily using classes in java.net package as well as popular HTTP client libraries e.g. HttpClient and HttpCore.
6. XML parsing libraries
There are many XML parsing libraries exists e.g. Xerces, JAXB, JAXP, Dom4j, Xstream etc. Xerces2 is the next generation of high performance, fully compliant XML parsers in the Apache Xerces family. This new version of Xerces introduces the Xerces Native Interface (XNI), a complete framework for building parser components and configurations that is extremely modular and easy to program. The Apache Xerces2 parser is the reference implementation of XNI but other parser components, configurations, and parsers can be written using the Xerces Native Interface. Dom4j is another flexible XML framework for Java application.
7. Excel reading libraries
Believe it or not but all real-world application has to interact with Microsoft office in some form or other. Many application needs to provide functionality to export data in Excel and if you have to do same from your Java application then you need Apache POI API.
8. Bytecode libraries
If you are writing framework or libraries which generate code or interact with bytecodes then you need a bytecode library. They allow you to read and modify bytecode generated by an application. Some of the popular bytecode libraries in Java world are javassist and Cglib Nodep. The Javassist (JAVA programming ASSISTant) makes Java bytecode manipulation very simple. It is a class library for editing bytecodes in Java. ASM is another useful bytecode editing library.

9. Database connection pool libraries
If you are interacting with the database from Java application but not using database connection pool libraries then you are missing something. Since creating connections at runtime takes time and makes request processing slower, its always advised to use DB connection libraries. Some of the popular ones are Commons Pool and JDBC. In a web application, it's web server which generally provides these functionalities but in core Java application you need to include these connection pool libraries into your classpath to use database connection pool.
10. Messaging libraries
Similar to logging and database connection, messaging is also a common feature of many real-world Java application. Java provides JMS, Java Messaging Service but that's not part of JDK and you need to include separate jms.jar. Similarly, if you are using third-party messaging protocol e.g. Tibco RV then you need to use a third-party JAR like tibrv.jar in your application classpath.
11. PDF Libraries
Similar to Microsoft Excel and World, PDF is another ubiquitous format. If you need to support PDF functionality in your application e.g. exporting data in PDF files then you can use the iText and Apache FOP libraries. Both provide useful PDF related functionality but iText is richer and better and I always preferred that one. See here to learn more about iText.
12. Date and Time libraries
Before Java 8, JDK's data and time libraries have so many flaws e.g they were not thread-safe, immutable, and error-prone and many Java developer relied on JodaTime for implementing their date and time requirement. From JDK 8, there is no reason to use Joda because you get all that functionality in the JDK 8's new Date and Time API itself.

13. Collection libraries
Even though JDK has a rich collection libraries, there are are some 3rd party libraries which provide more options e.g. Apache Commons Collections, Goldman Sachs collections, Google Collections, and Trove. The Trove library is particularly useful because it provides high speed regular and primitive collections for Java. FastUtil is another similar API, it extends the Java Collections Framework by providing type-specific maps, sets, lists and priority queues with a small memory footprint and fast access and insertion; provides also big (64-bit) arrays, sets, and lists, and fast, practical I/O classes for binary and text files.

14. Email APIs
The javax.mail and Apache Commons Email - provide an API for sending an email. It is built on top of the JavaMail API, which it aims to simplify.
15. HTML Parsing libraries
Similar to JSON and XML, HMTL is another common format many of us have to deal with. Thankfully, we have jsoup which greatly simplify working with HTML in Java application. You can use JSoup to not only parse HTML but also to create HTML documents. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. jsoup implements the WHATWG HTML5 specification and parses HTML to the same DOM as modern browsers do.
16. Cryptographic library
The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64 and Hexadecimal. In addition to these widely used encoders and decoders, the codec package also maintains a collection of phonetic encoding utilities.
17. Embedded SQL database library
H2 is a in-memory database, which you can embed in your Java application. They are great for testing your SQL scripts and running Unit tests which need a database. Apart from this, H2 is not the only DB, you also have Apache Derby and HSQL to choose from.
18. JDBC Troubleshooting libraries
There are some good JDBC Extension libraries exists which makes debugging easier e.g. P6spy. It is a library which enables database data to be seamlessly intercepted and logged with no code changes to the application. You can use these to log SQL queries and their timings. For example, if you are using PreparedStatment and CallableStatement in your code then these libraries can log an exact call with parameters and how much time it took to execute.
19. Serialization libraries
Google Protocol Buffer Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. It's richer and better alternative to Java serialization and I strongly recommend experienced Java developer to learn Google Protobuf.
20. Networking libraries
Some of the useful networking libraries are Netty and Apache MINA. If you are writing an application where you need to do low-level networking task, consider using these libraries.
Java Ecosystem is very vast and you will find tons of libraries for doing different things. You think about something and you will find there is a library exists to do just that. As always, Google is your best friend to find useful Java libraries but you can also take a look at Maven central repository to find some of the useful libraries for your task at hand.

Read More