Friday, 29 December 2017

Thread-safe Singleton in Java using Double Checked Locking Idiom

Singleton Pattern is one of the famous design patterns from the Gang of Four. Even though nowadays it is considered as an anti-pattern, it has served us well in the past. In Singleton pattern, a class has just one instance throughout its lifetime and that instance is shared between multiple clients. Singleton class has two responsibility, first to ensure that only instance of the class gets created and second, provide a method getInstance() so that everyone can get access to that single instance i.e. global access. One of the issue, faced by Singelton design pattern in the multi-threading program is to ensure that just one instance of the class gets created, even if multiple clients called getInstance() method same time. Many programmers solved this problem by making whole getInstance() method synchronized, which results in poor performance because every time a thread enters a synchronization method, it acquires the lock and while it's been inside the method, no other thread are allowed to enter, even if they are not creating instance and just accessing already created instance.

Wednesday, 27 December 2017

How to print leaf nodes of binary tree without recursion

You have learned how to print all leaf nodes of a binary tree in Java by using recursion and in this article, we'll solve the same problem without using recursion. Why should we do this? Well, it's a common pattern on programming job interview to solve the same problem using recursion and iteration. Since some problems are easy to solve using recursion e.g. tree based problems, tower of Hanoi, or Fibonacci series but their non-recursive solution is comparatively difficult, interviewer test candidates against this shift in the algorithm. If you have attended your computer science classes and enjoyed there, then you know that we can use Stack to convert a recursive algorithm to an iterative one. I'll use the same technique to print all leaf nodes of a binary tree without recursion.

Friday, 22 December 2017

How to pause Thread in Java using Sleep() and TimeUnit Example

There are multiple ways to pause or stop the execution of currently running thread, but putting the thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify?. Using those methods just for pausing thread is not good. Those are the tools for a conditional wait and they don't depend on upon time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait() method is different, they are designed for inter-thread communication in Java. By using sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why to wait and notify should not be used to pause the thread, a they need lock. You can only call them from a synchronized method or block and acquire and release a lock is not cheap.

Wednesday, 20 December 2017

How to convert String to Date Example in Java Multithreading

Data type conversion is one of the most common tasks in programming and a good programmer must know how to convert one type to another type. There are many times when you will be required to convert a String to java.util.Date object mostly in different format e.g. dd-MM-yy or yyyy-MM-dd or simply yyyy MM dd. For example, client pass dates as String to Server or sometimes we read Date related data from CSV file. Java provides API for parsing String to date using DateFormat class, though Java's Date and Time API is severely criticized, it is also the most used Date and Time format solution. Though Joda Date and Time API is always there and now Java 8 also got new date and time API, many of us don't have the luxury to use it in production. Many enterprise application is still running on Java 5 and Java 6, forget about JDK 7 or 8.

Monday, 18 December 2017

Difference between Daemon Thread vs User Thread in Java?

A thread is used to perform parallel execution  in Jaa e.g. while rendering screen your program is also downloading the data from the internet in the background. There are two types of threads in Java, user thread and daemon thread, both of which can use to implement parallel processing in Java depending upon priority and importance of the task. The main difference between a user thread and a daemon thread is that your Java program will not finish execution until one of the user thread is live. JVM will wait for all active user threads to finish their execution before it shutdown itself. On the other hand, a daemon thread doesn't get that preference, JVM will exit and close the Java program even if there is a daemon thread running in the background. They are treated as low priority threads in Java, that's why they are more suitable for non-critical background jobs. In this article, we will learn some key difference between user and daemon thread from Java multithreading and interview perspective.

Friday, 15 December 2017

Iterative Binary Tree PreOrder Traversal in Java - Without Recursion

This is the second article on binary tree pre-order traversal in Java. In the first part, I have shown you how to traverse a binary tree with pre-order traversal using recursion, and in this article, you will learn how to implement pre-order traversal without using recursion. Just to revise, pre-order is a depth-first algorithm, where the depth of the tree is first explored before traversing sibling. In preOrder traversal, first, node or root is visited, then left subtree, and right subtree, hence it is also known as NLR (Node-Left-Right) algorithm. You might know that when you use recursion, methods calls are stored in an internal Stack which unwinds itself when algorithm reaches the base case. When recursion is not allowed, you can use the Stack data structure to create the same effect, in fact, this is also a common technique to convert a recursive algorithm into an iterative one.

Wednesday, 13 December 2017

How to implement PreOrder traversal of Binary Tree in Java

The easiest way to implement the preOrder traversal of a binary tree in Java is by using recursion. The recursive solution is hardly 3 to 4 lines of code and exactly mimic the steps, but before that, let's revise some basics about a binary tree and preorder traversal. Unlike array and linked list which have just one way to traversed i.e. linearly, binary tree has several ways to traverse all nodes e.g. preorder, postorder and inorder. But, tree traversal algorithms are mainly divided into two categories, the depth-first algorithms, and breadth-first algorithms. In depth-first, you go deeper into a tree before visiting the sibling node, for example, you go deep following left node before you come back and traverse the right node. On breadth-first traversal, you visit the tree on its breadth i.e. all nodes of one level is visited before you start with another level top to bottom. The PreOrder, InOrder, and PostOrder traversals are all examples of depth-first traversal algorithms.

Monday, 11 December 2017

Java 8 compute() and computeIfPresent() Example

The JDK 8 has added several useful methods in existing interfaces e.g. java.util.Map, java.util.Collection, and java.util.concurrent.ConcurrentMap. Thanks to default methods, the much-needed evolution of existing interfaces become possible. Out of many useful methods, one method which stands out to me is the compute() method, which allows you to update a value in ConcurrentHashMap atomically. As per Java documentation, The compute() function tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). The entire function is performed atomically.

Friday, 8 December 2017

How to convert JSON String to Java Object - Gson/JSON Deserialization Example

You have learned how to convert a Java object to JSON String and in today's article, you will learn the opposite, i.e. converting a JSON String to Java object. The first example was known as JSON serialization example and this one is known as JSON deserialization because we are creating a Java object from a String. The idea is very similar to classical Serialization in Java where you convert a Java object to another binary format which can be transported over the network or can be saved in the disk for further usage. That's why the process of converting a Java object to JSON is known as serialization and converting a JSON document to Java object is known as De-Serialization. You can use any JSON library to perform serialization and de-serialization e.g. Jackson Databind, Gson, or Json-simple.  In this program, I'll show you how to use Gson to create a Java object from given JSON String.

Wednesday, 6 December 2017

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.

Monday, 4 December 2017

Java Optionals For More Expressive Code

Any of us who has programmed in a language that permits null references will have experienced what happens when you try to dereference one. Whether it results in a segfault or a NullPointerException, it’s always a bug. Tony Hoare described it as his billion-dollar mistake. The problem typically occurs when a function returns a null reference to a client that was unanticipated by the developer of the client. Say, in code like this:

Friday, 1 December 2017

What is class file in Java - How to create Class File

What is class file in Java


Class file in Java is compiled form of Java source file. When we compile Java program which is written in Java source file  ended with .java extension, it produces one more class files depending upon how many classes are declared and defined in that Java source file. One Java source file can only contain one public class and its name must match with name of file e.g. HelloWorld.java file can contain a public class whose name should be HelloWorld as shown below :