04/8/14
author

Classloading Mechanism in Java

Classes loading on Virtual Machine is a hidden process of any programming language. Most of the developers do not bother about it. Because this is the responsibility of frameworks to load their respective classes to run Virtual Machine and application on it. But believe me, this is really very important to know about classloaders and classloading mechanism. If you are writing higher end applications or frameworks, which has wide scope of work to do, there might be chance, you need to write your own custom classloaders for your applications. Lots of Java based frameworks have implemented their custom classloaders, which solve their concerned problems. Here we specifically talking about Java classloaders, Lets we discuss about classloading mechanism in Java Virtual Machine.

Class Loading on JVM

Classloading is a process to load required classes on Virtual Machine. Only after loading required classes your application can run on JVM. There are two types of classloading.

  1. Eager Classloading is process of loading all classes comprising the source of application before run the application on VM. Application can take some time to run on VM, because classloaders will first load all classes to VM and after that they will run application on VM.
  2. Lazy Classloading is process of loading classes, at first active use of class rather that loading them on start-up of application on VM.

The first active use of class occurs, when one of the following event occurs:

  • An instance of that class is created.
  • An instance of one of its subclass is initialized.
  • One of its static fields is initialized.

These two are the types of classloading on VM. But its totally depends of JVM vender that what types of classloading they are providing with their JVM. Note that, JVM provided by IBM supports both types of classloading but JVM provided by Oracle (Sun) is only support Lazy classloading.

java.lang.ClassLoader class

Before describe more about classloading mechanism in JVM, I would like to tell you somethings about java.lang.ClassLoader class, which will  help you to under classloading mechanism. According to JavaDoc, the class ClassLoader is an abstract class. If you want to create your own custom class loader for your application or framework then you can extend your classloader class from java.lang.ClassLoader class. There are methods available in ClassLoader class to load and define classes from file system. ClassLoader class load any class by its binary name and return java.lang.Class class object. Every java.lang.Class object contain reference of it ClassLoader.

java.lang.Class objects for array classes are not created by classloaders, but are created automatically as required by the Java runtime. The ClassLoader for an array class, as returned by Class.getClassLoader() is the same as the classloader for its element type; if the element type is a primitive type, then the array class has no ClassLoader.

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of classloader has an associated parent classloader. When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The Virtual Machine’s built-in class loader, called the “bootstrap classloader“, does not itself have a parent but may serve as the parent of a ClassLoader instance.

Class loaders that support concurrent loading of classes are known as parallel capable classloaders and are required to register themselves at their class initialization time by invoking the ClassLoader.registerAsParallelCapable() method. Note that the ClassLoader class is registered as parallel capable by default. However, its subclasses still need to register themselves if they are parallel capable.

In environments in which the delegation model is not strictly hierarchical, class loaders need to be parallel capable, otherwise class loading can lead to deadlocks because the loader lock is held for the duration of the class loading process (see loadClass methods).

Normally, the Java Virtual Machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the virtual machine loads classes from the directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass() converts an array of bytes into an instance of class java.lang.Class. Instances of this newly defined class can be created using Class.newInstance().

ClassLoaders Hierarchy 

Java has it own classloaders hierarchy to load classes on JVM. Java has three in-built classloaders, which are shown bellow in classloaders hierarchy diagram.

classloader_hierarchy

As you can see in above diagram, these three core classloaders communicate with each other through there hierarchy protocols, which I would mention later-on in this article. Now lets understand about particular classloader individually, their hierarchy and responsibilities:

  • Bootstrap classloader : Bootstrap classloader is core native classloader of Java. This is the topmost  classloader of classloaders hierarchy, it wouldn’t be wrong, if would say, this is the parent of every classloader in Java, like java.lang.Object class is parent class of every class in Java. Because this is native classloader, therefore it’s implementation could be vary with different JVMs. Native classloaders are mostly implemented in C language. Bootstrap classloader is responsible to load all available classes in rt.jar file, which is located at $JAVAHOME/jre/lib/rt.jar
  • Extension classloader: Extension classloader come done next to Bootstrap classloader, in other word, this is child classloader of Bootstrap classloader. It is implemented by sun.misc.Launcher$ExtClassLoader class. This classloader is responsible to load all classes available in ext folder, which is located at  $JAVAHOME/jre/lib/ext/*.jar or any other directory specified by java.ext.dirs system property.
  • System classloader: System classloader is also known as Application classloader. It is implemented by sun.misc.Launcher$AppClassLoader class, which come done next to Extension classloader. This is child classloader of Extension classloader. The main responsibility of this classloader is to load all available classes in $CLASSPATH or java.class.path  location.
  • User Defined ClassLoaders: User defined or Custom classloader are those classloaders, which are defined by developers itself for their applications or frameworks. If you want to create your own classloader then you have to extend your classloader class by java.lang.ClassLoader class. These custom classloaders will come done under System classloader in hierarchy. Their class loading responsibility would be defined by the developers.

Classloading Procedures

This is very important and interesting to understand, how does JVM load any class internally. Till now you almost clear about ClassLoaders, their hierarchy and their individual responsibilities. Now its time to understand communication between classloaders, their overall class loading mechanism and workflow. Now have smile, lets go little deep and understand it better.

Whenever JVM instantiate any class, then JVM will load this class, this is known as Lazy classloading. JVM uses a delegation model to load classes.  Basic idea of delegation model is that classloader has a parent classloader, when classloader load a class, it first delegate the search for class to its parent classloader, before attempting to find the class itself.

class-loading-mechanism

Classloading is a recursive process, When a classloader get request to load a class, it will initiate class loading. First of all it pass the request to it parent classloader, if that parent class loader has any of its parent classloader then it will pass request to its parent classloader and so on. Such way topmost classloader in hierarchy will first search that class in its directory and its cache ( Every ClassLoader maintain its own cache ), whether this class is already been loaded by this classloader, if yes then classloader will return class from cache, otherwise classloader will find that class in its directory. If class exist there in directory, it will store that class in its cache and return that class to its child classloader and so on. In other hand, if parent classloader did not find that class in its directory and cache, it will throw ClassNotFoundException. Now its child classloader catch this exception and try to find that class in its directory location. The same procedure will go on until that class would not found by any classloader in that hierarchy. If still that class is not available in overall hierarchy of classloader, eventually classloader, who initiate class loading will throw ClassNotFoundException and stop the execution.

There are few observations about classloading, which are important in this classloading mechanism:

  • Parent classloader has always opportunities to load class first.
  • Each classloader maintain their own cache and check any class first in its cache, if it is not available in cache then check it in its directory and try to load it.
  • It is ensure that one classlaoder can only see classes loaded by itself or by its parent classloaders, but  not by its children and siblings classloaders.

ClassLoader Call Flow

In previous section of this article you have learnt about classloading mechanism. Now you are aware about how does classloading take place internally in JVM. In this section, I would like to explain, how custom classloader are implemented by extending java.lang.ClassLoader class and what is the ClassLoader’s methods call flow to load and define a class in JVM.

There are three important methods of ClassLoader class, which play significant role to load and define a class in JVM. These methods of ClassLoader class are given bellow:

  1. public Class<?> loadClass(String name) throws ClassNotFoundException;
  2. protected Class<?> findClass(String name) throws ClassNotFoundException;
  3. protected final Class<?> defineClass(String name, byte[] b, int off, int len) throws ClassFormatError;

Whenever a ClassLoader is created, it is assigned a parent ClassLoader. As per parent delegation model, when client invoke loadClass(String name) method of ClassLoader class, it will call the loadClass method of parent ClassLoader, where is classloading algorithms is implemented. Before JDK 1.2, loadClass method was abstract, every ClassLoader was required to provide its own classloading algorithm. But later on it is observed that class loading is a critical, complicated and important for JVM, therefore since JDK 1.2 JVM introduced parent delegation model and provide default implementation for loadClass method. After that loadClass method invoke findClass(String name) method of ClassLoader class. Every Custom or User Defined ClassLoader should override findClass(String name) method to specify custom location, where classes need to be search before loading. The findClass method invoke search for given class in specified location, if class found, it read that class and return bytecodes of the class. This bytecodes of class is passed as byte array to the defineClass(String name, byte[] b, int off, int len) method, defineClass method returns java.lang.Class class, which define that given class. This java.lang.Class instance can be used to instantiate that class in Java application. This is the way, how a class get loading and defined in JVM.

Conclusion

This article describes, how important a classloading mechanism is to understand, if you a Java developer. This articles explain entire important aspects regarding classloading and ClassLoaders. After reading this article you can create your own ClassLoader, which suites to your applications. Hope you would like this article. This article encourages you to go more deep in concepts.





03/31/14
author

What is difference between ClassNotFoundException and NoClassDefFountError in Java?

This is one of the most popular interview questions of Java. If you are a Java professional, everybody will expect from you that you would be aware about ClassNotFoundException and NoClassDefFoundError. Because, both are very important in Java application development and have significant differences. Lets discuss differences in both Exception and Error.

crash

1. As you can easily guess that ClassNotFoundException is 'Excetion', while NoClassDefFoundError is 'Error'. If you want to know difference between Error and Exception, you can read my blog here.

2. ClassNotFoundException is thrown, when application tries to load any class by its String name and that class does not found. This exception thrown when below mentioned methods of given classes get called by String name of a class:

  • The forName(String className) method of class Class.
  • The forName(String name, boolean initialize, ClassLoader loader) method of class Class.
  • The loadClass(String className) method of class ClassLoader.
  • The loadClass(String className, boolean resolve) method of class ClassLoader.
  • The findClass(String className) method of class ClassLoader.
  • The findSystemClass(String className) method of class ClassLoader.

NoClassDefFoundError is thrown, when ClassLoader instance tries to load definition of class and no definition of class found. This error happens if class definition existed when the currently executing class was compiled with that definition, but the definition is no longer available. This error thrown when below mentioned methods of ClassLoader class get called:

  • The defineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain) method of class ClassLoader.
  • The defineClass(String name, ByteBuffer b, ProtectionDomain protectionDomain) method of class ClassLoader.

3. ClassNotFoundException is an Exception in Java, which could be happened due to wrong input at runtime. For example at runtime when user trying to load any class by reflective call and that class name does not exist. That means, class name is invalid (wrong input), but this case is recoverable, you can write and alternative mechanism for this.

NoClassDefFoundError is an Error in Java, which could happened, when any source is compiled successfully but at runtime any required class file would not found. This may be happen sometime during distribution of JARs. For example, at the time of compilation, all classes are exists and source get compiled successfully, but at time of distribution any class file got missed for JAR. In this case, when JVM try to load and create the definition of missing class, NoClassDefFoundError will get raise. This is really a serious problem, because there is no recoverable procedures for errors. JVM will not run application properly if distributed classes are not available. Therefore it is necessary to repackage that distributed JAR and try again.

Conclusion

Therefore, ClassNotFoundException and NoClassDefFoundError are very important to know, because at the time of Java application development, you may encounter with these problems, which are very common problems. Knowing all the facts about them will reduce your time to resolve these types of issues and you can write robust code by tackling these issue at very first level of development.





03/28/14
author

What is UnSupportedClassVersionError in Java?

Few day back one of my friend call me and asked about one error in his Java program. He told me, his program is throwing UnSupportedClassVersionError. At that time he was not aware about this error, because this error does not occur much frequently as other exception and error like ClassNotFoundException and NoClassDefFoundError. But this is one of important error, you must know about. Therefore, let us discuss UnSupportedClassVersionError more deeply. If you want to know what is difference between Error and Exception, please read my blog here.

error

java.lang.UnSupportedClassVersionError is subclass of java.lang.ClassFormatError and this is the subclass of java.lang.LinkageError and which is subclass of java.lang.Error class. Class hierarchy of UnSupportedClassVersionError is illustrated below:

java.lang.Error

java.lang.LinkageError

java.lang.ClassFormatError

java.lang.UnSupportedClassVersionError

JavaDocs

According to javadoc of java.lang.LinkageError class “Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.“

According to javadoc of java.lang.ClassFormatError class “ ClassFormatError thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.”

According to javadoc of java.lang.UnSupportedClassVersionError class “ UnsupportedClassVersionError thrown when an attempt is made to load a class with a format version that is not supported by the JVM.”

Example

Exception in thread "main" java.lang.UnsupportedClassVersionError: 
    GenerateInvoice (Unsupported major.minor version 49.0)
        at java.lang.ClassLoader.defineClass0(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)

Reason

What is the reason of UnSupportedClassVersionError? As you can see this error is somewhere related to class version as it’s name suggesting us. This error occurs, when JVM is not capable to understand the format of class file and ClassLoader reject class to load in JVM.

Now question arise why ClassLoader reject any Java class to load in JVM? This is because, if class compilation version of JDK and version of JVM where you want to load is different then is error occurs. Means, if any class is compiled with any upper version of JDK, i.e JDK1.6 and you are trying to load that particular class in lower version JVM i.e JDK1.5, then ClassLoader will throw UnSupportedClassVersionError because JVM is not able to understand upper version format. But vice-versa is not true here, because class compiled with lower version of JDK can be loaded in upper versions of JVM, because upper version JVM gives lower version support.

Resolution

There are few resolution for UnSupportedClassVersionError, you have to select , what suits you in your scenario.

1. If you have source code you class, then you can compile that class in your JDK version accordingly.

2. One easiest way to install same version of JDK, which was used to compile particular JAR or Class or you can install latest version of JDK.

3. If you think JDK version is correct then check your JAVA_HOME and PATH environment variables.

How to find the java compiler target version from a java class file?

Every Java class has to version associated with it one in major version and other is minor version. For example 45.3, where 45 is major version and 3 is minor version. Java major and minor version list is given below according to associated JDK versions.

  1. JDK 1.0 → major version 45 and minor version 3
  2. JDK 1.1 → major version 45 and minor version 3
  3. JDK 1.2 → major version 46 and minor version 0
  4. JDK 1.3 → major version 47 and minor version 0
  5. JDK 1.4 → major version 48 and minor version 0
  6. J2SE 5.0 → major version 49 and minor version 0
  7. J2SE 6.0 → major version 50 and minor version 0
  8. J2SE 7.0 → major version 51 and minor version 0
  9. J2SE 8.0 → major version 52 and minor version 0

If you want to know compiler target version of Java class. There is one command according to Operating System (UNIX/ Linux/ Windows).

On UNIX/ Linux:

javap -verbose MyClass

or

javap -verbose MyClass | grep “major”

On Windows:

javap -verbose MyClass

or

javap -verbose MyClass | findstr “major”

This is the command, which can help you to find compiler target version of JDK. So these are only few things what you have to remember to tackle this error in future. I hope you would like this article and it will help you somewhere in future.





03/19/14
author

Why float and double are not correct data types for monetary and financial calculation?

When we do write code to hold decimal point value in any variable, first data types come in our mind are float and double. Which is obvious because float and double data types are designed to hold floating points (Fractional Numbers). But only most experienced developers know that float and double are not correct data types to hold any monetary (currency) or financial value. This issue is not only exists in Java programming language. But issue is present in every language which use native floating point to hold decimal values. Therefore it is important to choose appropriate data types to hold such values and perform operations on them. Otherwise your minor mistake can lead a erroneous result.

Now question arise, why float and double are not correct data types to hold currency and financial values?

Answer is float and double data types are designed to hold binary floating values for scientific calculations. If we elaborate it more, that means float and double are represent binary values with base 2 multiplier. While monetary (currency) or financial values are decimal values with base 10 multiplier. Which is major difference with both types of decimal values.

Let us understand little more about float data type and how this data type works and hold binary values internally. As you know, IEEE 754 representation of float is 32 Bit data type. It dedicate 1 Bit to store sign of value ( -ve or +ve ), next 8 Bits to store exponent for the base of 2 and rest all 23 Bit for ( Mantissa ) multiplier of evaluated base.

single-floating-point

Similarly, double is 64 Bit data types. It dedicate 1 Bit to store sign of value (-ve or +ve), next 11 Bits to store exponent for the base of 2 and rest all 52 Bits for (Mantissa) multiplier of evaluated base.

double-floating-point

Formula representation for binary floating point number is:

Floating Point Number = Sign * 2Exponent * Mantissa

Therefore if we have to represent a number 10.25 in floating point it will be represent this number internally as

10.25 = + * 2-4 * 164

While, monetary (currency) and financial decimal values are evaluated on base 10. Therefore, if we have to store decimal financial values, we need represent like this:

Floating Point Number = Sign * 10Exponent * Mantissa

To represent number 10.25 in decimal floating point, its representation will be like this.

10.25 = + * 10-2 * 1025

This is the main issue, that is why, we cannot correctly represent monetary decimal values in float and double data types. But there is an alternative way through which you can achieve this in Java with java.math.BigDecimal class. Similarly, in C# there is decimal data type. Lets see one example which could explain this problem better:

package com.hawk.java;

import java.math.BigDecimal;

/**
 * This class shows, how decimal values can behave weird
 * with different types of data types and how to resolve 
 * this issue in Java.
 *
 * @author SoManyWord.com
 */

public class FloatingPoint {

	private double number1 = 10.45;
	private double number2 = 9.30;

	private BigDecimal decNum1 = new BigDecimal(10.45);
	private BigDecimal decNum2 = new BigDecimal(9.30);

	private BigDecimal decimalNum1 = new BigDecimal("10.45");
	private BigDecimal decimalNum2 = new BigDecimal("9.30");

	public void subtractDoubleValues() {
		System.out.println("Subtraction With Double Data Types : " + (number1 - number2));
	}

	public void subtractBigDecimalValuesWithDoubleConstructor() {
		System.out.println("Subtraction With Double Constructor of Big Decimal Class : " + (decNum1.subtract(decNum2)));
	}

	public void subtractBigDecimalValuesWithStringConstructor() {
		System.out.println("Subtraction With String Constructor of Big Decimal Class : " + (decimalNum1.subtract(decimalNum2)));
	}

	public static void main(String[] args) {

		FloatingPoint floatingPoint = new FloatingPoint();
		floatingPoint.subtractDoubleValues();
		floatingPoint.subtractBigDecimalValuesWithDoubleConstructor();
		floatingPoint.subtractBigDecimalValuesWithStringConstructor();

	}
}

Outputs


Subtraction With Double Data Types : 1.1499999999999986
Subtraction With Double Constructor of Big Decimal Class : 1.149999999999998578914528479799628257751464843750
Subtraction With String Constructor of Big Decimal Class : 1.15

This example shows you how double data type and BigDecimal class behave differently. You assume that subtraction will be (10.45 – 9.30 = 1.15). But in case of double is output is 1.1499999999999986.  Initially this value difference is looking minor error, but later on when you will do further operations on this value this minor error will become big and could spoil your all calculation. Therefore, if you want to avoid this situations, there are some points which can help you to avoid this issue.

  1. If possible use long or int data types instead of double and float. For example, $10.55 can be convert in to 1055 cents. Which give you more precise calculation.
  2. If you are using Java as programming language to perform monetary calculations, use BigDecimal class instead of float and double. In case of C# language you can use decimal data type.
  3. Use String constructor of BigDecimal class instead of double constructor of BigDecimal class.

These are few points which is necessary to know to write correct and robust code.





03/18/14
author

What is difference between sleep and wait methods in Java?

Java-concurrency

This is most frequently asked questions in Java telephonic interviews. Because this is very basis question about java programming. Both methods sleep(long millis) and wait() looks alike, means both method halt program execution. But there are huge differences in both methods. Let us discuss them.

  1. sleep(long millis) is method of java.lang.Thread class, while wait() is method of java.lang.Object class.
  2. sleep(long millis) is static method, while wait() is non-static method.
  3. Most significant difference is sleep(long millis) method halt the execution of current thread till given milliseconds. but current thread does not leave monitor on synchronized resource and does not allow other threads to execute on synchronized resource. While wait() method halt the execution of current thread till another thread notify or wake up this thread with notify() and notifyAll() methods of java.lang.Object class. wait() method leave the monitor on synchronized resource and allow other threads to take lock on synchronized resource.
  4. sleep(long millis) method basically used to halt execution for specific time while wait() and nofity() methods are used for inter threads communications.
  5. sleep method has two overloaded variants sleep(long millis) and sleep(long millis, int nanos), while wait method has three overloaded variants wait(), wait(long timeout) and wait(long timeout ,int nanos).




03/6/14
author

Why 64 Bit operations are not thread safe in Java?

java-synchronization

When you do work in multi-threaded environment in Java. There are lots of things you need to keep in mind to write your code correct and safe. You expect that your code will give you correct output in concurrent execution environment. But there are lots of things which could might be goes wrong in multi-threaded applications. If you want to know more about these things you can read my blog “Common problems of concurrency (Multi-Threading) in Java”. But here we are specifically talking about 64 Bit operations in multi-threaded environment. It is important to know about 64 Bit data types how they work internally, which will help us to write correct and robust code.

Whenever a thread read any variable without synchronization, it may read some stale value from variable, but at least it will read some value what any other thread write on variable, whether it is fresh or stale. This safety guarantee is known as out-of-thin-air safety. Out-of-thin-air safety applies to all variables except from 64 Bit variables ( double, long ). All 64 Bit variables which are not declared volatile are unsafe to use in multiple threads. Any operation on non-atomic and non-volatile 64 Bit variable is break down in two separate 32 Bit operations by JVM. Therefore if read and write occurs in two different threads, it is possible that read of non-volatile long or double return the higher 32 bits of one value and the lower 32 bits of another. Thus, even if you don’t care about stale values, it is still not safe to use shared mutable long and double variables in multi-threaded programs unless they are declared volatile or guarded by a lock, because in this case it may give you totally wrong value which does not belong to program.

If you are using 64 Bit variables in your multi-threaded environment please make sure your variable must be volatile or synchronized. In short, it is necessary to make 64 Bit variable atomic, so no other thread can interfere, if any thread is writing on 64 Bit variables. Hope this will help you to write robust code for concurrent environment in Java.





03/2/14
author

Common problems of concurrency (Multi-Threading) in Java

Java-concurrency

Writing correct program is hard and writing correct concurrent program is harder. There are lots of things that can go wrong in concurrent program than a sequential program. Concurrency (Threading) is very important feature of Java. If you are interested to write concurrent program in Java, then there are lots of things what you have to take care about. Therefore, I would like to cover some common problems, which you could might be encounter with in concurrency. These are some points which are important to understand about concurrent programming. It is necessary to know about reasons and solutions for these problems. I have taken help from really a good book (Java Concurrency In Practice) for concurrent programming in Java to write this blog. Let us discuss these problems one by one.

1. Atomicity

In concurrent environment two or many threads can run concurrently, if all threads are trying to update some shared resource concurrently, there might be chance that threads trying to read shared resource get stale data and produce wrong outputs. To resolve this issue, it is necessary to make such critical code atomic. Atomicity is to create any operation atomic, in such way that operation can be performed in a single attempt. If a critical section of code is getting execute by only one thread at a time and no other thread can enter in this section until that thread complete its execution. That means this critical section is atomic. You can make any critical section of code atomic by synchronization.

2. Visibility

Visibility of shared object could be different for different threads. This is one of the problems of multi-threading environment. Suppose there are two threads, one is writing any shared variable and other is reading from shared variable. When reading and writing will be occur in different threads, there is no guarantee that reader thread will see the value written by writer thread. This problem of multi-threading is known as visibility issue of shared resource. This problem can be resolved with proper synchronization of shared resource.

3. Ordering

Order of execution of code can be different as it is written in class. Because JVM rearrange this code according to its convenience, that is known as reordering. Today’s machines do run on multiple processors. To utilize these processors JVM split code to run with different processors, therefore order of code could be change during execution. There might be change that any critical section of code can generate wrong result after reordering of code. If you do not want to change the order of execution of code written then you will have to synchronize your critical code.

4. Race Conditions

A race condition occurs when the correctness of computation depends on the relative time or interleaving of multiple threads by the runtime. In other words, when getting the right answers relies on lucky timing. The most common type of race condition is check-then-act, where a potentially stale observation is used to make a decision on what to do next. You can resolve this problem by make your critical section atomic using proper synchronization.

5. Livelock

Livelock is a form of liveness failure in which a thread, while not blocked, still cannot make progress because it keeps retrying an operation that will always fail. Livelock often occurs in transaction a messaging applications, where the messaging infrastructure rolls back a transaction if a message cannot be processed successfully, and puts it back at the head of the queue.

6. Starvation

Starvation occur when a thread is denied and not getting access to resource to progress its task. The most common starved resource is CPU cycles. Starvation in Java application can be caused by inappropriate use of thread priorities. For example two thread of same priority is trying to access a common resource and each thread allowing other thread to have its access first. In such situation no thread could get access of resource. That means both threads are suffering from starvation.

7. Deadlock

Deadlock occur when two of many thread are waiting for two or more resources, where each thread need to get access on all resources to progress and those resources are acquired by different threads and waiting for other resources to be release, which will not be possible ever. For example, two threads A and B need both resources X and Y to perform their tasks. If thread A acquires resource X and thread B acquires Y and now both threads are waiting for resources to be release by other thread. Which is not possible and this is called deadlock. You need to take care of the way of your synchronization if this is going to be a cause of deadlock.

Conclusion

These are few common problems which are most frequently occurs in concurrency in Java. You need to take care about proper synchronization of your code in multi-threaded environment otherwise it could be a cause of big issues. If you want to know more about these issues deeply, you could read my upcoming blogs on same problems with deep detail on issues and their appropriate solutions to make threading robust in Java.





02/20/14
author

How to handle exceptions in thread environment in Java?

exception-handlingExceptions handling of single-threaded and multi-threaded programs are different from each other. When single-threaded program terminates due to uncaught exception, it stop running and print exception stack trace on console. In other hand, when multi-threaded program encounter with uncaught exception, the stack trace may be printed, but no one may be watch that console. Because when that thread fail, application may appear continuously working. Therefore, there might be change that its failure may go unnoticed.

Exception is an unavoidable conditions, which can be occur in program due to lots of reasons. In threading application, we write our task in run() method of Thread class or Runnable interface. As you know run() method is an overridden method, that is why we can not throw any exception from run() method. Therefore all exceptions must be handle in side that run() method. Most of time we used methods of other classes as task in our run() method. In that case we would only aware about checked exceptions which are declared with signature of any methods. But there might be change that any method can throw RuntimeException. Any poor written code can throw NullPointerException from inside the method. These type of tasks should be call with in try and catch block that catch unchecked exceptions or with in try and finally block to ensure that if the thread exits abnormally the program is informed of this and can take corrective action.

There are two way to handle exceptions in Java threads. One is already mentioned above, with try, catch and finally block. Here is an example of same case. In this coding example you can see how to handle exception in thread and how to write recovery procedure for that.

public class ThreadManager extends Thread{

	@Override
	public void run() {
		Throwable thrown = null;
		try {
			while (!isInterrupted())
				// Run tasks until there is no task in Work Queue.
				runTask(getTaskFromWorkQueue());
		} catch (Throwable ex) {
			thrown = ex;
		} finally {
			// threadExited() method is recovery procedure 
			//if any exception occurs.  
			threadExited(this, thrown);
		}
	}

	public static void main(String[] args) {
		ThreadManager threadManager = new ThreadManager();
		threadManager.start();
	}

}

Above mentioned approach is proactive approach to the problem of unchecked exceptions. Where as Thread class it self provide UncaughtExceptionHandler facility. This handler let us detect when a thread dies due to an uncaught exception. Thread class has exposed and interface Thread.UncaughtExceptionHandler. We can implement this interface and set this implementation to any thread  Thread.setUncaughtExceptionHandler( UncaughtExceptionHandler eh ), so that thread can call that implementation, if any uncaught exception raise.

If we are not able to set exception handler to a particular  thread (For example, we are not able to create thread in thread pools), then you can set a default handler to thread with static method of thread Thread.setDefaultUncaughtExceptionHandler( UncaughtExceptionHandler eh ) .

Let me show you an coding example for both, to set an exception handler on particular thread and default exception handler using thread pool.

ExceptionThrowerRunnable.java

package com.hawk.java.thread;

/**
 * Demonstrates exceptions occurring inside a thread.
 *
 * @author SoManyWord.com
 */
public class ExceptionThrowerRunnable implements Runnable {

	public void run() {
		// This task will always throw an IllegalStateException
		throw new IllegalStateException("Running this is never legal.");
	}

}

LoggingThreadExceptionHandler.java

package com.hawk.java.thread;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handle exceptions uncaught in threads by logging them.
 * @author SoManyWord.com
 */
public class LoggingThreadExceptionHandler implements Thread.UncaughtExceptionHandler {

	private Logger logger = Logger.getLogger("MYLOGGER");

	public void uncaughtException(Thread t, Throwable e) {
		logger.log(Level.ALL, "Error { "+ e +" } in Thread { "+ t +" } was uncaught.");
		e.printStackTrace();
	}
}

ThreadRunner.java

This class has set uncaught exception handler on particular thread.

package com.hawk.java.thread;

/**
 * Execute the threading application to demonstrate exception handling.
 * @author SoManyWord.com
 */
public class ThreadRunner {

	/**
	 * Start the application.
	 *
	 */
	public static void main(String[] args) {

		Thread thread = new Thread(new ExceptionThrowerRunnable());
		thread.setUncaughtExceptionHandler(new LoggingThreadExceptionHandler());
		thread.start();
	}
}

PoolRunner.java

This class has set a default uncaught exception handler on threads using thread pool.

package com.hawk.java.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Execute the tasks using thread pools.
 * @author SoManyWord.com
 *
 */
public class PoolRunner {

	/**
	 * Execute the {@link ExceptionThrowerRunnable} a couple of times in a pool.
	 */
	public static void main(String[] args) {
		// Set the default uncaught exception handler, 
                // If you are not able to set handler to a particular thread. 
		Thread.setDefaultUncaughtExceptionHandler(new LoggingThreadExceptionHandler());

		ExecutorService pool = Executors.newFixedThreadPool(2);

		Runnable r = new ExceptionThrowerRunnable();

		for(int i = 0; i < 10; i++) {
			pool.execute(r);
		}
	}
}

Now you know how to handle uncaught exceptions in thread environment. Either you could set handler on particular thread or you could set default handler as well. This default handler will be call if no other handler is set on thread. Hope this blog will help you to write robust code in multi-threading environment.





02/15/14
author

How to create and implement custom annotations in Java?

java-annotationAnnotations are the most important feature of Java. There are lots more Java based frameworks available, which are working on annotations. For example JUnit, Hibernate, Spring etc. These few are most famous frameworks designed with the help of annotations. Therefore knowledge of annotations is quite necessary if you are working on Java.

“Annotation are tags or meta-data, which can be inserted in to source code. So that it could be process at runtime and can take decision according to that annotations.”

Java compiler understands couple of annotations, which we would discuss later in this article. But most important thing is to create own annotations or custom annotations. Lets see an example, how to create custom annotations in Java.

Annotation can be define with same way as we define interface but in case of annotation @interface keyword is used. Let us figure out some important points about custom annotation

1. @interface keyword is used to create annotation

2. Only public or default access modifier can be used for annotation.

3. Only public or abstract access modifier can be used for attributes of Annotation.

4. Only primitive types, String, Class, EnumAnnotation and one dimensional arrays of mentioned types are permitted as attributes in annotations.

5. Default value can be defined for attributes.

6. Four types of meta-annotation are used for custom annotation. Which are @Documented@Inherited, @Target and @Retention. These meta-annotations descriptions are mentioned below in this article.

package com.hawk.java;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author SoManyWord.com
 */
@Documented
@Inherited
@Target (ElementType.METHOD)
@Retention (RetentionPolicy.RUNTIME)
public @interface MethodMetaData {

	public String methodName();
	public int arguments() default 0;
	public Class<? extends Exception> expected() default java.lang.Exception.class;
	public String Author();

}

Code shown above is coding example of custom annotations. This is how you can create your own annotation in Java. Now its time to discuss more about meta-annotations used in custom annotation creation.

Meta-annotations of Annotations

There are four types of meta-annotations used to create custom annotations. According to javadoc these meta-annotations are describe as mentioned bellow:

@Documented: Indicates that annotations with a type are to be documented by javadoc and similar tools by default. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.

@Inherited: Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation.

Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from super classes; annotations on implemented interfaces have no effect.

@Target: Indicates the kinds of program element to which an annotation type is applicable. If a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element. If such a meta-annotation is present, the compiler will enforce the specified usage restriction. For example, this meta-annotation indicates that the declared type is itself a meta-annotation type. It can only be used on annotation type declarations rather then class, method or field. ElementType type enum is used to assign its values as mentioned in above example. For example @Target (value = ElementType.METHOD). ElementType enum has many more values available, use them accordingly.

@Retention: Indicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS.

For Example: RetentionPolicy.RUNTIME Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

In-Built Annotations in Java

Java has some in-built annotations, which are known for Java compiler. There are three types of in-built annotations in Java. Let us discuss something more about these in-built annotations. According to javadoc these in-built annotations are describe as mentioned bellow:

@Override: Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

@Deprecated: A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code.

@SuppressWarnings: Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element). Note that the set of warnings suppressed in a given element is a superset of the warnings suppressed in all containing elements. For example, if you annotate a class to suppress one warning and annotate a method to suppress another, both warnings will be suppressed in the method.

As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.

Coding Example of Annotation Implementation in Java

This is time to create and use annotation in real life. Now we will see that how can we create an annotation? How to use annotation? How to use annotation at runtime and make decision on basis of annotation?

I hope most of you have used unit test framework JUnit, which use annotations to create test cases and execute them. If you didn’t use it, not a big reason to worry. Let us take an example, suppose we have a class called Maths, which have two methods sum(int a, int b) and divide(int a, int b) which support mathematics add and divide operations. Method divide(int a, int b) throws a custom exception BadParametersException, if any number is divided by zero, it is a invalid operation. In such case if method throws BadParametersException exception, means test case must be pass, because it is a valid case to throw an exception in such scenario. Therefore, I have created a @Test annotation with Expected attribute, which accept any kind to exception class, if method throws same exception, means test case is pass. This is the same way how this scenario is handled in JUnit. Let us try to resolve this case in our way.

Test.java (Annotation)

package com.hawk.java;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author SoManyWord.com
 */
@Documented
@Inherited
@Target (value = ElementType.METHOD)
@Retention (RetentionPolicy.RUNTIME)
public @interface Test {

	/**
	 * This field except <code>Class</code> type of any custom <code>Exception</code>.
	 * This annotation attribute is used whether method throw assigned custom <code>Exception</code>
	 * or not. If method throws custom <code>Exception</code>, it means test case is pass. 
	 * @return
	 */
	public Class<? extends Exception> Expected() default java.lang.Exception.class;

}

BadParametersException.java

package com.hawk.java;

/**
 * The class <code>BadParametersException</code> is sub-class of <code>Exception</code> class.
 * This class is used to throw exception if method arguments are invalid to process.
 * @author SoManyWord.com
 */
public class BadParametersException extends Exception {

	private String message = null;

	public BadParametersException() {
		super();
	}

	public BadParametersException(String message) {
		super(message);
		this.message = message;
	}

	public BadParametersException(Throwable throwable) {
		super(throwable);
	}

	@Override
	public String toString() {
		return this.message;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

}

Maths.java

package com.hawk.java;

/**
 * General math class, which support few mathematical operations.
 * @author SoManyWord.com
 */
public class Maths {

	public int sum(int a, int b) {
		return a + b;
	}

	public float divide(int a, int b) throws BadParametersException{
		if (b == 0) {
			throw new BadParametersException("Invalid patameter exception: No number can be divide by 0.");
		}
		float c = a/b;
		return c;
	}

}

UnitTests.java

package com.hawk.java;

/**
 * All test cases are written here with @Test annotation.
 * @author SoManyWord.com
 */
public class UnitTests {

	@Test(Expected = BadParametersException.class)
	public void testDivide() throws BadParametersException {
		Maths math = new Maths();
		math.divide(5, 0);
	}

	@Test
	public void testSum() {
		Maths math = new Maths();
		int sum = math.sum(10, 5);
		if (sum == 15)
			System.out.println("Sum Tast Case Pass, Output Value Is: " + sum);
	}

}

TestRunner.java

package com.hawk.java;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * This class is test suite runner. This class runs all test cases
 * provided in given test class. In main method test class is mentioned.
 * This class particularly check custom exception thrown by method. If thrown exception
 * match with expected exception mentioned on attributes of @Test annotation, that means
 * test case is pass. This same scenario is used in JUnit as well.
 * @author SoManyWord.com
 */
public class TestRunner {

	public void runUnitTests(String className) {
		try {
			Class<?> testClass = Class.forName(className);
			Object object = testClass.newInstance();
			Method[] methods = testClass.getMethods();
			for (Method method : methods) {
				if (method.isAnnotationPresent(com.hawk.java.Test.class)) {
					Test annotation = method.getAnnotation(com.hawk.java.Test.class);
					Class<? extends Exception> expectedClass = annotation.Expected();
					if (expectedClass != null) {
						try {
							method.invoke(object);
						}catch ( InvocationTargetException ex ) {
							if ( ex.getTargetException().getClass() == expectedClass ) {
								System.out.println("Test Case Pass With Custom Exception (BadParametersException): " + ex.getTargetException().getLocalizedMessage());
							} else {
								System.out.println("Test Case Fail With An Exception: " + ex.getMessage());
							}
						} catch ( Exception ex ) {
							System.out.println("Test Case Fail With An Exception: " + ex.getMessage());
						}
					}
				}
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		TestRunner testRunner = new TestRunner();
		testRunner.runUnitTests("com.hawk.java.UnitTests");
	}

}

output


Test Case Pass With Custom Exception (BadParametersException): Invalid patameter exception: No number can be divide by 0.

Sum Tast Case Pass, Output Value Is: 15




02/10/14
author

How to design Singleton Pattern using Java?

Singleton pattern is one most commonly used pattern in every types of software application developments. Therefore every interviewer would like to ask about this pattern first. This is really simple design pattern to create but you need to take care of some common things to design this pattern. Before going deep, let us concentrate on singleton pattern definition.

“Singleton pattern provides the possibility to control the number of instances (mostly one) that are allowed to be create.”

singleton-desi-pattern

As you can see definition of singleton pattern describe singleton as special kind to class which allow only limited number of objects creation. Most of time singleton allows only one instance for whole application as its name is suggesting “Singleton” means single object. Only instance is used throughout application.

What is the significance of singleton?

Now question arise that where to use this pattern and what is significance of singleton pattern? Singleton is used where you want to control limited number of objects creation. Sometime applications have few heavy objects of particular classes, Therefore application cannot afford to create new heavy objects every time to perform any action. For example we use application context, session factory and database factory, which do not allow us to create any instance. When we ask for instance if no instance is available then it will create an instance and return, if is available and already create then it will return same instance again to use.

How to create singleton class?

Before creating singleton class you need to take care few points about singleton. Let discuss these points.

  1. Singleton class does not allow to create any instance directly. Therefore all constructors in class must be declared private, so that no client can create its new instance directly.
  2. There must be a public static method which returns an object of same class. For example,  public static SingletonClass getInstance(); This method responsible to create and return an object of singleton class. If instance is already present (instance is not null) then it will return same instance otherwise it will create an instance and return it to client and keep it to further use in application.
  3. One most important thing to arrange your code this way, so that there must not be any change of creating second object of class.

To understand this you can see implementation of singleton class below

Coding Example

Here I would like to show you an example of File Logger, which would be a singleton class and will provide only single object throughout
application to log any error.

package com.hawk.java.patterns;

/**
 * FileLogger is a singleton class and will provide
 * only single object throughout application to log any error.
 *
 * @author SoManyWord
 *
 */
public class FileLogger {

        private static volatile FileLogger logger;

        /**
         * Prevent client for using any constructor and create object directly.
         */
        private FileLogger() {

        }

        /**
         * Create and return singleton object.
         * @return FileLogger
         */
        public static FileLogger getInstance() {
                if (logger == null) {
                        synchronized (FileLogger.class) {
                                if ( logger == null ) {
                                        logger = new FileLogger();
                                }
                        }
                }
                return logger;
        }

        /**
         * Log message to the text file.
         * @param message String message.
         */
        public synchronized void log(String message) {
                //Write to log file.
        }
}

This is coding example which would help you to understand singleton class internal design.