Saturday 20 August 2016

Detect Deadlock Programmatically in Your Applicaion

What is a Deadlock ?

It is a condition where two or more threads are blocked forever because they are waiting for each other to get the lock/resource. And it happens because of the inappropriate use of mutual exclusion locks.
So let's see a sample of code where a deadlock situation is created intensionally for demonstrate purpose.
 
Output :


Here you can observe both th threads are waiting for each other to get the lock.

How to detect deadlock threads in your application?

Well, so Java has given default tools with the JDK package; using those we can detect the thread dumps which are in deadlock state. And also there are so many 3rd party tools available in market you can use for the same. 

Here we will discuss about Java's default tool and how programmatically we can detect deadlock.

Detect deadlock programmatically :

OK, so let's create a daemon thread which runs in background and detects if there is any deadlock thread and prints.
This is a thread which runs in background as daemon thread till the JVM is alive and repeatedly detects deadlock in every 5 seconds. 

Java 5 introduced new classes under package java.lang.management
ThreadMXBean : The management interface for the thread system of the Java virtual machine.
ManagementFactory : This is a factory class to get ThreadMXBean instance.
ThreadInfo : This class contains basic thread info like thread ID and thread name.

Now let's add the detector thread to the main program :
Output:
 

 

Detect deadlock using Java's default tools :

Using jconsole :
Java has provided jconsole tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jconsole

Step 2 : Select process name with PID and click Connect

Step - 3 : Select Thread tab and click Detect Deadlock

Final output window:
 

Using jstack :

Java has provided jstack  tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jstack <PID>
Ex : ../bin/$ jstack 17472 
Output:


That's all for this post. Please feel free to give your comment/suggestion. Thank you.
 

Wednesday 17 August 2016

Why enum is the best approach to implement a Singleton class ?

In my previous blog (Implement SIngleton class in an efficient way), we have already discussed about all the approaches to implement a singleton class and concluded with the enum type implementation. As mentioned earlier enum is completely safe from reflection and serialization attack.

Now we will see in details that,
- Is enum really safe
- Whether we can break an enum from singleton with either reflection or serialization.

Before proceeding to this let's know more about enum in depth.

OK, what you think about this simple enum ? What is exactly an enum ?

Well, an enum is a simple class which extends java.lang.Enum class. Believe me this is the truth behind enum keyword. Java compiler plays the main role here while compiling the enum; it converts the enum to a normal class and extends that class directly from Enum class rather than Object class. Now let's check the truth.

So, the compiler injects 3 more elements (2 methods and 1 static block).

Let's try to instantiate an enum using java Reflection API.

Test class
Output
 
Here the exception is because of private constructor. Since public/protected constructors are not allowed inside an enum, the default access scope of a constructor is private inside an enum. So it fails to instantiate directly.
Let's try by modifying the access scope of constructor.
Output

Now this time the exception is because, inside java.lang.reflect.Constructor.newInstance(Object ... initargs), there is a condition check like below :

 So there is no way to instantiate an enum using reflection.

Let's try to make copy of an enum instance.
Test class
Output
 
Now you can observe few things:
- hash code f both the objects are same
- state of the object got changed after it being serialized, but the changes are reflected in the deserialized object. So it is clear that the state of an enum instance is not serialized but the name by calling java.lang.Enum.name(). And while deserializing it gets only the name of the instance and by calling java.lang.Enum.valueOf() method it gets the actual enum instace.

Conclusion : enum type is a special class which can not be instantiated outside of the enum class in all possible way.


Please feel free to give your comment/suggestion. Thank you.

Tuesday 16 August 2016

Implement Singleton class in an efficient way

Singleton design pattern

This is one of the creational patterns described by GoF. This pattern ensures that a class must have one and only one instance provided a global access point to it and also with lazy initialization (initialization on first use).

So, to meet the above requirements, few steps of implementation are coming into our mind :
  • define private no-argument constructor
  • declare private static variable of the class type as instance and initialize
  • define a public static method as access point of the instance and return the instance
Approach -  1 (Eager Initialization)

This is the simplest implementation of a singleton class. But the concerns here are :
1. Eager initialization
2. Missing exception handling if there is chances of getting any exception during object construction

Approach - 2 (Eager Initialization with Exception handling)
Here the exception handling is included but still is an eager initializsation. To achieve lazy initialization, we have to instantiate the object on demand (on first access). 

Approach - 3(Lazy Initialization with Exception handling)

Here both above concerns are addressed (lazy initialization and exception handling) and the code looks fine. But it doesn't mean this is the efficient implementation. This implementation has so many concerns :
1. Not thread safe
2. Can be broken by serialisation if the class is serializable 

For thread safe, that we can achieve through synchronisation (either by defining synchronized method or synchronized block with double check lock while instantiating the object). 
Approach - 4
And in the previous approach (Approach - 1 and Approach - 2), during the eager initialization, the implementation is completely safe in multi threaded environment as the object is instantiated during the class loading. But we can't achieve the lazy initialization in this approach. To overcome this Bill Pugh came up with a new approach to create singleton class using a static inner class. 
Approach - 5 (Bill Pugh's approach using static inner class to achieve thread safety and lazy loading)
Here SingletonHelper class is a static inner class. And this will not be loaded with the Singleton class. When ever the Singleton.getInstance() method will be invoked, and the SingletonHelpet.instance will be access for the first time,  the helper class will be loaded at the same time. Using this approach the lazy initializaton is achieved easily and also thread safe.

Now, let's discuss about the other concern - "Can be broken by serialisation if the class is serializable". Here we can apply Java's magic method trick to resolve these kind of problems. Java provided some hidden and tricky method ( readResolver() ) for developer to replace the deserialized object with the required object.
Approach - 6 
The readResolve() is called when ObjectInputStream reads the object from stream and trying to return to the caller. Here we have returned the SingletonHelper.instance, so the deserialized object will be replaced by this instance.

After all these approach, you might have decides already to go with the Approach - 6 as it overcomes all the concerns :
1. No more eager initialization
2. Thread safe in multi threaded environment
3. Safe with Serialization

After all looks fine, now we will discuss about the real devil for all these approaches that is Java Reflection. This is the mechanism by which any kind of class (even with private constructor, private members)  are also can be accessed by creating new instance of that class. So the above approach can be broken with this mechanism. 

To overcome this, we have to go for the best approach for implementing singleton class proposed by Joshua Bloch in Effective Java "a single-element enum type is the best way to implement a singleton".
Approach - 7 (The best for Serialization/Reflection attacks but eager initialization)
 
Here in this above example I have demonstrated the same previous required singleton class using enum type. 

The below are the reasons why this approach is the best to implement a singleton class.
     1. Java gives guarantee that enum can not be broken by Reflection API : We can not create 
         instance of an enum using Reflection API
     2. Serialization process is different for enum than a normal class : During serialization,         
         ObjectOutputStream writes the value returned by enum constant's name() method. And to      
         deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the 
         deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing 
         the constant's enum type along with the received constant name as arguments.  

Above all benefits, still enum type approach has the concern of eager initialization. We can not achieve Lazy Initialization in this approach but more robust for serialization/reflection attack. If you have more concerns about eager initialization, then you can go with Approach - 6 but again the devil (reflection API) can pull it down.



Please feel free to give your comment/suggestion. Thank you.

Monday 8 August 2016

Power of Lambda Expression and Function Programing in Java 8

Functional Programing is the most powerful concept introduced in Java 8. And this can be only achieved by Lambda Expression.

Now, you may get W2H in your mind. Hold on, "W2H" is not any chemistry terminology. I just refer as W2H means (What, Why and How). I mean you are now thinking about "What is Lambdas, Why Lambdas, and How to use Lambdas ?".

Before discussing on Lambdas in details, I just want you to feel the power of it using some examples. Each example here I have prepared with 2 snippet of codes, first is without Java 8 and followed by Java 8 style implementation.

I have a list of employees here with members(id, name, salary, doj, location, dept, permanent/contractor).
Employee{empId='EMP001', name='Mr. Alpha', salary=24000.0, deptName='Product Development', isPermanent=true, doj=Mon Dec 12 00:00:00 IST 2011, location='Chennai'}
Employee{empId='EMP002', name='Mr. Beta', salary=43000.0, deptName='Support', isPermanent=false, doj=Mon Jul 02 00:00:00 IST 2012, location='Chennai'}
Employee{empId='EMP003', name='Mr. Gama', salary=66000.0, deptName='Product Development', isPermanent=false, doj=Mon Dec 30 00:00:00 IST 2013, location='Bangalore'}
Employee{empId='EMP004', name='Mr. Theta', salary=54000.0, deptName='Quality Engineer', isPermanent=true, doj=Wed Sep 12 00:00:00 IST 2012, location='Hyderabad'}
Employee{empId='EMP005', name='Mr. Delta', salary=58000.0, deptName='Support', isPermanent=true, doj=Tue Apr 23 00:00:00 IST 2013, location='Hyderabad'}


These examples are demonstrated the power of Lambda Expression and Functional style of programming. We will discuss in depth how it works for better understanding.  

Stay tuned for more updates.....

Friday 5 August 2016

Folder Watcher using java.nio.file.WatcherService

A simple folder inspector/watcher which logs the user action into a file.
User actions includes :
- Create
- Modify
- Delete

Here we are going to discuss on few new classes introduced as part of java.nio package with Java 1.7
- java.nio.file.Path : This represents typically represent a system dependent file path to locate a file in a file system.
- java.nio.file.WatchService : It a service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
- java.nio.file.WatchEvent : An event for an object that is registered with a WatchService.
- java.nio.file.WatchKey : A token representing the registration of a watchable object with a WatchService. Here Path is a watchable object which will be watched by WatchService.
- java.nio.file.FileSystems : Factory methods for file systems.
- java.nio.file.FileSystem : It is an interface to a file system and is the factory for objects to access files and other objects in the file system.

FolderWatcher.java

Output:dir-log.txt