Вы находитесь на странице: 1из 55

What is final in Java?

Final variable , Method and Class Example

Final in java is very important keyword and can be applied to class, method, and variables in Java. In
this java final tutorial we will see what is final keyword in Java, what does it mean by making final
variable, final method and final class in java and what are primary benefits of using final keywords in
Java and finally some examples of final in Java. Final is often used along with static keyword in Java to
make static final constant and you will see how final in Java can increase performance of Java

Example of Final variable, Final method and Class in Java

What is final keyword in Java?

Final is a keyword or reserved word in java and can be applied to member variables,
methods, class and local variables in Java. Once you make a reference final you are not allowed to
change that reference and compiler will verify this and raise compilation error if you try to reinitialized final variables in java.
What is final variable in Java?
Any variable either member variable or local variable (declared inside method or block) modified by
final keyword is called final variable. Final variables are often declare with static keyword in java and
treated as constant. Here is an example of final variable in Java
public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error
Final variables are by default read-only.
What is final method in Java
Final keyword in java can also be applied to methods. A java method with final keyword is called
final method and it can not be overridden in sub-class. You should make a method final in java if you
think its complete and its behavior should remain constant in sub-classes. Final methods are faster
than non-final methods because they are not required to be resolved during run-time and they are
bonded on compile time. Here is an example of final method in Java:
class PersonalLoan{
public final String getName(){
return "personal loan";
class CheapPersonalLoan extends PersonalLoan{
public final String getName(){
return "cheap personal loan"; //compilation error: overridden method is final

What is final Class in Java

Java class with final modifier is called final class in Java. Final class is complete in nature and can not
be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper
classes. Here is an example of final class in java
final class PersonalLoan{
class CheapPersonalLoan extends PersonalLoan{
from final class

//compilation error: cannot inherit

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:
1. Final keyword improves performance. Not just JVM can cache final variable but also application
can cache frequently use final variables.
2. Final variables are safe to share in multi-threading environment without additional synchronization
3. Final keyword allows JVM to optimized method, variable or class.

Final and Immutable Class in Java

Final keyword helps to write immutable class. Immutable classes are the one which can not be
modified once it gets created and String is primary example of immutable and final class which I have
discussed in detail on Why String is final or immutable in Java. Immutable classes offer several
benefits one of them is that they are effectively read-only and can be safely shared in between
multiple threads without any synchronization overhead. You can not make a class immutable without
making it final and hence final keyword is required to make a class immutable in java.

Example of Final in Java

Java has several system classes in JDK which are final, some example of final classes are String,
Integer, Double and other wrapper classes. You can also use final keyword to make your code better
whenever it required. See relevant section of java final tutorial for example of final
variable, final method and final class in Java.

Important points on final in Java

1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure
to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.
5. Only final variable is accessible inside anonymous class in Java.
6. Final method can not be overridden in Java.
7. Final class can not be inheritable in Java.
8. Final is different than finally keyword which is used on Exception handling in Java.
9. Final should not be confused with finalize() method which is declared in object class and called
before an object is garbage collected by JVM.
10. All variable declared inside java interface are implicitly final.
11. Final and abstract are two opposite keyword and a final class can not be abstract in java.
12. Final methods are bonded during compile time also called static binding.
13. Final variables which is not initialized during declaration are called blank final variable and must be
initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain
as "final variable (name) might not be initialized".
14. Making a class, method or variable final in Java helps to improve performance because JVM gets
an opportunity to make assumption and optimization.
15. As per Java code convention final variables are treated as constant and written in all Caps e.g.
private final int COUNT=10;
16. Making a collection reference variable final means only reference can not be changed but you can
add, remove or change object inside collection. For example:
private final List Loans = new ArrayList();
list.add(home loan); //valid
list.add("personal loan"); //valid
loans = new Vector(); //not valid
Thats all on final in Java. We have seen what final variable, final method is and final class in Java
and what does those mean. In Summary whenever possible start using final in java it would result in
better and faster code.

How to use Comparator and Comparable in Java? With example

Comparator and Comparable in Java Examples
Difference between Comparator and Comparable in Java is very popular Java interview question mostly asked in
telephonic round and writing code to sort object using Comparable or Comparator is popular on written test round of
interview.The question was this How you will sort Employee object based on his EmployeeID and his name and
this involves the use of both Comparable as well as Comparator interface in Java. This post is my revision on Java
fundamentals similar to I did about equals method in Java and some tips to override hashCode in Java. All of these
methods are fundamentals in Java programming language and correct understanding is must for any Java
developer.Comparators and comparable in Java are two interfaces which is used to implement sorting in Java. Its
often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we

need to use either compare() or compareTo() method defined in

java.util.Comparator and java.lang.Comparable. In this Java tutorial we will see example of Comparator
and Comparable to sort object in Java and discuss some best practices around when to use Comparator interface
etc. Any way before moving ahead Lets see some important differences between Comparable and Comparator in

Comparator vs Comparable in Java

Here are some of the common differences, which is worth remembering to answer this question if asked
during a telephonic or face to face interview:
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined
in java.lang package, which very much says that Comparator should be used as an utility to sort objects
which Comparable should be provided by default.
2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
While Comparable interface has method public int compareTo(Object o) which returns a negative integer,
zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him,
while Comparable interface compares "this" reference with the object specified. I have shared lot of tips on how to
override compareTo() method and avoid some common mistakes programmer makes while implementing
Comparable interface.
4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper
classes implements Comparable interface.Its always good practice to override compareTo() for value objects.
5) If any class implement Comparable interface in Java then collection of that object either List or Array can be
sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based
on there natural order defined by CompareTo method.
6)Objects which implement Comparable in Java can be used as keys in a SortedMap like TreeMap or elements in
a SortedSet for example TreeSet, without specifying any Comparator.
These were combination of some theoretical and practical differences between Comparator and Comparator interface
in Java. It does help you to decide when to use Comparator vs Comparable but things will be more clear when we
some best practices around using both of these interfaces. Now lets see an example of Comparator in Java:

Example of using Comparator and Comparable in Java

So in Summary if you want to sort objects based on natural order then use Comparable in Java and if you want
to sort on some other attribute of object then use Comparator in Java. Now to understand these concepts lets see
an example or real life coding:

1) There is class called Person, sort the Person based on person_id, which is primary key in database

2) Sort the Person based on there name.

For a Person class, sorting based on person_id can be treated as natural order sorting and sorting based on
name field can be implemented using Comparator interface. To sort based on person_id we need to
implement compareTo() method.

public class Person implements Comparable {

private int person_id;
private String name;
* Compare current person with specified person
* return zero if person_id for both person is same
* return negative if current person_id is less than specified one
* return positive if specified person_id is greater than specified one
public int compareTo(Object o) {
Person p = (Person) o;
return this.person_id - o.person_id ;
Generally you should not use difference of integers to decide output of compareTo method as result of integer
subtraction can overflow but if you are sure that both operands are positive then its one of the quickest way to
compare two objects. See my post things to remember while overriding compareTo in Java for more tips on
And for sorting based on person name we can implement compare(Object o1, Object o2) method of Java
Comparator class.
* Comparator implementation which sorts Person objects on person_id field
public class SortByPerson_ID implements Comparator{
public int

compare(Object o1, Object o2) {

p1 = (Person) o;
p2 = (Person) o;
p1.getPersonId() - p2.getPersonId();

Similar guidelines applies while implementing compare() method as well and instead of using subtraction operator,
its better to use logical operator to compare whether two integers are equal to, less than or greater than. You can
write several types of Java Comparator based upon your need for example
reverseComparator , ANDComparator , ORComparator etc which will return negative or positive number
based upon logical results. String in Java even provides an special comparator
called CASE_INSENSITIVE_ORDER, to perform case insensitive comparison of String objects.

How to Compare String in Java

String is immutable in Java and one of the most used value class. For comparing String in Java we should not be
worrying because String implements Comparable interface and provides a lexicographic implementation
for CompareTo method which compare two strings based on contents of characters or you can say in lexical order.

You just need to call String.compareTo(AnotherString) and Java will determine whether specified String is
greater than , equal to or less than current object. See my post 4 example to compare String in Java for alternatives
ways of comparing String.

How to Compare Dates in Java

Dates are represented by java.util.Date class in Java and like String, Date also implements Comparable in
Java so they will be automatically sorted based on there natural ordering if they got stored in any sorted collection like
TreeSet or TreeMap. If you explicitly wants to compare two dates in Java you can
call Date.compareTo(AnotherDate) method in Java and it will tell whether specified date is greater than , equal
to or less than current String. See my post 3 ways to compare Dates in Java for more alternatives of comparing two
When to use Comparator and Comparable in Java
At last lets see some best practices and recommendation on when to use Comparator or Comparable in Java:
1) If there is a natural or default way of sorting Object already exist during development of Class than
use Comparable. This is intuitive and you given the class name people should be able to guess it correctly like
Strings are sorted chronically, Employee can be sorted by there Id etc. On the other hand if an Object can be
sorted on multiple ways and client is specifying on which parameter sorting should take place than
use Comparator interface. for example Employee can again be sorted on name, salary or department and clients
needs an API to do that. Comparator implementation can sort out this problem.
2) Some time you write code to sort object of a class for which you are not the original author, or you don't have
access to code. In these cases you can not implement Comparable and Comparator is only way to sort those
3) Beware with the fact that How those object will behave if stored in SorteSet or SortedMap like TreeSet
and TreeMap. If an object doesn't implement Comparable than while putting them into SortedMap, always provided
corresponding Comparator which can provide sorting logic.
4) Order of comparison is very important while implementing Comparable or Comparator interface. for example if
you are sorting object based upon name than you can compare first name or last name on any order, so decide it
judiciously. I have shared more detailed tips on compareTo on my post how to implement CompareTo in Java.
5) Comparator has a distinct advantage of being self descriptive for example if you are writing Comparator to
compare two Employees based upon there salary than name that comparator as SalaryComparator, on the other
hand compareTo()

Difference between ArrayList and Vector in Java

ArrayList and Vector are two of most used class on java collection package and difference between Vector
and ArrayList is one of the most frequently asked java interview question on first round or phone interview. Though
its quite a simple question in my opinion but knowledge of when to use Vector over ArrayList or does matter if you
are working on a project. In this article we will some point based difference between Vector and ArrayList in
Java and trying to understand the concept behind those differences. Ultimate goal is to familiarize yourself
with distinguish property of ArrayList and Vector. By the way Java 5 adds another implementation
of List interface which is similar to Vector andArrayList but provides better concurrency access than Vector, its
called CopyOnWriteArrayList. By the way this is the third article on discussing about Collection interview
question, Difference between LinkedList and ArrayList and List vs Set are other popular interview questions based
upon collection framework in Java.

Before seeing differences between Vector and ArrayList, let's see some similarities between these two and why
we can use ArrayList in place of Vector on certain scenario.

1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the
object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.
4) ArrayList and Vector also allows null and duplicates.

Vector vs ArrayList in Java

Now let's see some key difference between Vector and ArrayList in Java, this will decide when is the right time
to use Vector over ArrayList and vice-versa. Differences are based upon properties like synchronization, thread
safety, speed, performance , navigation and Iteration over List etc.
1) Synchronization and thread-safety
First and foremost difference between Vector and ArrayList is that Vector is synchronized and ArrayList is not, what
it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which
makes it thread-safe and allows it to be used safely in a multi-threaded and concurrent environment. On the other
hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment. This is also
a popular interview question on thread, where people ask why ArrayList can not be shared between multiple threads.

2) Speed and Performance

ArrayList is way faster than Vector. Since Vector is synchronized and thread-safe it pays price of
synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes
it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded
environment if multiple threads are only reading values from ArrayList or you can create read only ArrayList as well.

3) Capacity
Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field
while you can increase size of ArrayList by calling ensureCapacity () method.
4) Enumeration and Iterator
Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to
Iterator and ListIterator returned by ArrayList. I have discussed this point in detail on my post What is difference
between Iterator and Enumeration, you can also look there.

5) Legacy
Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of
Collection framework but in later version it's been re-factored to implement List interface so that it could become part
of collection framework
After considering these points about both Vector and ArrayList , my conclusion is use ArrayList wherever possible
and avoids use of Vector until you have no choice. Think for CopyOnWriteArrayList over Vector, if you have multiple
readers and few writers because it can provide thread-safety without impacting performance too much.

What is difference between HashMap and Hashtable in Java?

HashMap vs Hashtable in Java
Though both Hashtable and HashMap are data-structure based upon hashing and
implementation of Map interface, main difference between them is that HashMap is
not thread-safe but Hashtable is thread-safe. Which means you cannot use HashMap in
multi-threaded Java application without external synchronization. Another difference
is HashMap allows one null key and null values but Hashtable doesn't allow null key or
values. Also thread-safety of hash table is achieved using internal synchronization,
which makes it slower than HashMap. By the way difference between HashMap and
Hashtable in Java is one of the frequently asked in core Java interviews
to check whether candidate understand correct usage of collection classes and aware
of alternative solutions available. Along with How HashMap internally works in
Java and ArrayList vs Vector, this is one of the oldest question from Collection
framework in Java. Hashtable is a legacy Collection class and it's there in Java API
from long time but it got re-factored to implement Map interface in Java 4 and from
there Hashtable became part of Java Collection framework. Hashtable vs HashMap in
Java is so popular a question that it can top any list of Java Collection interview
Question. You just can't afford not to prepare HashMap vs Hashtable before going
to any Java programming interview. In this Java article we will not only see
some important differences between HashMap and Hashtable but also some
similarities between these two collection classes. Let's first see How different they
are :

Difference between HashMap and Hashtable in Java

Both HashMap and Hashtable implements Map interface but there are some significant
difference between them which is important to remember before deciding whether to
use HashMap or Hashtable in Java. Some of them is thread-safety, synchronization and
speed. here are those differences :
1.The HashMap class is roughly equivalent to Hashtable, except that it is non
synchronized and permits nulls. (HashMap allows null values as key and value
whereas Hashtable doesn't allow nulls).
2. One of the major differences between HashMap and Hashtable is that HashMap is
non synchronized whereas Hashtable is synchronized, which means Hashtable is
thread-safe and can be shared between multiple threads but HashMap can not be
shared between multiple threads without proper synchronization. Java 5
introduces ConcurrentHashMap which is an alternative of Hashtable and provides
better scalability than Hashtable in Java.
3. Another significant difference between HashMap vs Hashtable is that Iterator in
the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and

throw ConcurrentModificationException if any other Thread modifies

the map structurally by adding or removing any element except Iterator's
own remove() method. But this is not a guaranteed behavior and will be done by
JVM on best effort. This is also an important difference between Enumeration and
Iterator in Java.
4. One more notable difference between Hashtable and HashMap is that because
of thread-safety and synchronization Hashtable is much slower than HashMap if used
in Single threaded environment. So if you don't need synchronization and HashMap is
only used by one thread, it out perform Hashtable in Java.
5. HashMap does not guarantee that the order of the map will remain constant over

HashMap and Hashtable : note on Some Important Terms

1)Synchronized means only one Thread can modify a hash table at one point of time.
Basically, it means that any thread before performing an update on a Hashtable will
have to acquire a lock on the object while others will wait for lock to be released.
2) Fail-safe is relevant from the context of iterators. If an Iterator or ListIterator has
been created on a collection object and some other thread tries to modify the
collection object "structurally", a concurrent modification exception will be thrown. It
is possible for other threads though to invoke "set"method since it doesn't modify the
collection "structurally". However, if prior to calling "set", the collection has been
modified structurally, "IllegalArgumentException" will be thrown.
3) Structurally modification means deleting or inserting element which could
effectively change the structure of map.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
In Summary there are significant differences between Hashtable and HashMap in Java
e.g. thread-safety and speed and based upon that only use Hashtable if
you absolutely need thread-safety, if you are running Java 5 consider
using ConcurrentHashMap in Java.

How Volatile in Java works? Example of volatile keyword in Java

How to use Volatile keyword in Java
What is volatile variable in Java and when to use Volatile variable in Java is famous
multi-threading interview question in Java interviews. Though many programmer
knows what is a volatile variable but they fail on second part i.e. where to
use volatile variable in Java as its not common to have clear understanding and
hands-on on volatile in Java. In this tutorial we will address this gap by providing

simple example of volatile variable in Java and discussing some when to

use Volatile variable in Java. Any way Volatile keyword in Java is used as an indicator
to Java compiler and Thread that do not cache value of this variable and always read
it from main memory. So if you want to share any variable in which read and
write operation is atomic by implementation e.g. read and write in int or boolean
variable you can declare them as volatile variable. From Java 5 along with major
changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces
some change in Java Memory Model (JMM), Which guarantees visibility of changes
made by one thread to another also as "happens-before" which solves the problem of
memory writes that happen in one thread can "leak through" and be seen by another
thread. Java volatile keyword cannot be used with method or class and it can only be
used with variable. Java volatile keyword also guarantees visibility and ordering ,
after Java 5 write to any volatile variable happens before any read
into volatile variable. By the way use of volatile keyword also prevents compiler or
JVM from reordering of code or moving away them from synchronization barrier.

Volatile variable Example in Java

To Understand example of volatile keyword in java lets go back to Singleton pattern
in Java and see double checked locking in Singleton with Volatile and
without volatile keyword in java.
* Java program to demonstrate where to use Volatile keyword in Java.
* In this example Singleton Instance is declared as volatile variable to
* every thread see updated value for _instance.
* @author Javin Paul
public class Singleton{
private static volatile Singleton _instance; //volatile variable
public static Singleton getInstance(){
if(_instance == null){
if(_instance == null)
_instance = new Singleton();
return _instance;

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time

2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating
instance of Singleton is not able to communicate other thread, that instance has been
created until it comes out of the Singleton block, so if Thread A is creating Singleton
instance and just after creation lost the CPU, all other thread will not be able to see
value of _instance as not null and they will believe its still null.

Why? because reader threads are not doing any locking and until writer thread comes
out of synchronized block, memory will not be synchronized and value
of _instance will not be updated in main memory. With Volatile keyword in Java
this is handled by Java himself and such updates will be visible by all reader threads.
So in Summary apart from synchronized keyword in Java, volatile keyword is also used
to communicate content of memory between threads.

Lets see another example of volatile keyword in Java

most of the time while writing game we use a variable bExit to check whether user
has pressed exit button or not, value of this variable is updated in event thread and
checked in game thread , So if we don't use volatile keyword with this variable ,
Game Thread might miss update from event handler thread if its not synchronized in
java already. volatile keyword in java guarantees that value of volatile variable will
always be read from main memory and "happens-before" relationship in Java Memory
model will ensure that content of memory will be communicated to different
private boolean bExit;
while(!bExit) {


In this code example One Thread (Game Thread) can cache the value
of "bExit" instead of getting it from main memory every time and if in between any
other thread (Event handler Thread) changes the value; it would not be visible to this
thread. Making boolean variable "bExit" as volatile in java ensures this will not

When to use Volatile variable in Java

One of the most important thing in learning of volatile keyword is understanding when
to use volatile variable in Java. Many programmer knows what is volatile variable and
How does it work but they never really used volatile for any practical purpose. Here
are couple of example to demonstrate when to use Volatile keyword in Java:
1) You can use Volatile variable if you want to read and write long and double variable
atomically. long and double both are 64 bit data type and by default writing of
long and double is not atomic and platform dependence. Many platform perform write
in long and double variable 2 step, writing 32 bit in each step, due to this its possible
for a Thread to see 32 bit from two different write. You can avoid this issue by making
long and double variable volatile in Java.
2) Volatile variable can be used as an alternative way of achieving synchronization in
Java in some cases, like Visibility. with volatile variable its guaranteed that all reader
thread will see updated value of volatile variable once write operation completed,
without volatile keyword different reader thread may see different values.
3) volatile variable can be used to inform compiler that a particular field is subject to
be accessed by multiple threads, which will prevent compiler from doing any
reordering or any kind of optimization which is not desirable in multi-threaded
environment. Without volatile variable compiler can re-order code, free to cache
value of volatile variable instead of always reading from main memory. like following
example without volatile variable may result in infinite loop
private boolean isActive = thread;
public void printMessage(){
System.out.println("Thread is Active");

without volatile modifier its not guaranteed that one Thread see the updated value
of isActive from other thread. compiler is also free to cache value
of isActive instead of reading it from main memory in every iteration. By
making isActive a volatile variable you avoid these issue.
4) Another place where volatile variable can be used is to fixing double checked
locking in Singleton pattern. As we discussed in Why should you use Enum as
Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java

1. volatile keyword in Java is only application to variable and using volatile keyword
with class and method is illegal.
2. volatile keyword in Java guarantees that value of volatile variable will always be
read from main memory and not from Thread's local cache.
3. In Java reads and writes are atomic for all variables declared using Java volatile
keyword (including long and double variables).
4. Using Volatile keyword in Java on variables reduces the risk of memory consistency
errors, because any write to a volatile variable in Java establishes a happens-before
relationship with subsequent reads of that same variable.
5. From Java 5 changes to a volatile variable are always visible to other threads.
Whats more it also means that when a thread reads a volatile variable in Java, it sees
not just the latest change to the volatile variable but also the side effects of the code
that led up the change.
6. Reads and writes are atomic for reference variables are for most primitive variables
(all types except long and double) even without use of volatile keyword in Java.
7. An access to a volatile variable in Java never has chance to block, since we are only
doing a simple read or write, so unlike a synchronized block we will never hold on to
any lock or wait for any lock.
8. Java volatile variable that is an object reference may be null.
9. Java volatile keyword doesn't means atomic, its common misconception that after

declaring volatile ++ will be atomic, to make the operation atomic you still need to
ensure exclusive access using synchronized method or block in Java.
10. If a variable is not shared between multiple threads no need to use volatile
keyword with that variable.

Difference between synchronized and volatile keyword

in Java
What is difference between volatile and synchronized is another popular core Java
question asked in multi-threading and concurrency interviews. Remember volatile is
not a replacement of synchronized keyword but can be used as an alternative in
certain cases. Here are few differences between volatile and synchronized keyword
in Java.
1. Volatile keyword in Java is a field modifier, while synchronized modifies code
blocks and methods.
2. Synchronized obtains and releases lock on monitors Java volatile keyword doesn't
require that.
3. Threads in Java can be blocked for waiting any monitor in case of synchronized,
that is not the case with volatile keyword in Java
4. Synchronized method affects performance more than volatile keyword in Java.
5. Since volatile keyword in Java only synchronizes the value of one variable between
Thread memory and "main" memory while synchronized synchronizes the value of all
variable between thread memory and "main" memory and locks and releases a
monitor to boot. Due to this reason synchronized keyword in Java is likely to have
more overhead than volatile.
6. You can not synchronize on null object but your volatile variable in java could be
7. From Java 5 Writing into a volatile field has the same memory effect as a monitor
release, and reading from a volatile field has the same memory effect as a monitor
In Summary volatile keyword in Java is not a replacement of synchronized block or
method but in some situation is very handy and can save performance overhead which
comes with use of synchronization in Java

Difference between Thread vs Runnable interface in Java

Thread vs Runnable in Java is always been a confusing decision for beginners in java. Thread in
Java seems easy in comparison of Runnable because you just deal with one
class java.lang.Thread while in case of using Runnable to implement Thread you need to deal with both
Thread and Runnable two classes. though decision of using Runnable or Thread should be taken
considering differences between Runnable and Thread and pros and cons of both approaches.
This is also a very popular thread interview questions and most of interviewer are really interested to
know what is your point of view while choosing Thread vs Runnable or opposite. In this java article we
will try to point out some differences between Thread and Runnable in Java which will help you to take
an informed decision.

Difference between Thread and Runnable interface in

Thread vs Runnable in Java
Here are some of my thoughts on whether I should use Thread or Runnable for implementing task
in Java, though you have another choice as "Callable" for implementing thread which we will discuss
1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so
once you extended Thread class you lost your chance and can not extend or inherit another class in
2) In Object oriented programming extending a class generally means adding new functionality,
modifying or improving behaviors. If we are not making any modification on Thread than use Runnable
interface instead.
3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or
any other means. so logical separation of Task as Runnable than Thread is good design decision.
4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from
different means. since you can not restart a Thread once it completes. again Runnable vs Thread for
task, Runnable is winner.
5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have
worker thread which executes those task.
6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be
done easily with Runnable.
These were some of notable difference between Thread and Runnable in Java, if you know any
other differences on Thread vs Runnable than please share it via comments. I personally use Runnable
over Thread for this scenario and recommends to use Runnable or Callable interface based on your

Difference between ConcurrentHashMap, Hashtable and Synchronized Map

in Java
ConcurrentHashMap vs Hashtable vs Synchronized Map
Though all three collection classes are thread-safe and can be used in multi-threaded,
concurrent Java application, there is significant difference between them, which
arise from the fact that how they achieve their thread-safety. Hashtable is a legacy
class from JDK 1.1 itself, which uses synchronized methods to achieve thread-safety.
All methods of Hashtable are synchronized which makes them quite slow due to
contention if number of thread increases. Synchronized Map is also not very different
than Hashtable and provides similar performance in concurrent Java programs. Only
difference between Hashtable and Synchronized Map is that later is not a legacy and
you can wrap any Map to create it's synchronized version by
using Collections.synchronizedMap() method. On the other hand,
ConcurrentHashMap is especially designed for concurrent use i.e. more than one

thread. By default it simultaneously allows 16 threads to read and write

from Map without any external synchronization. It is also very scalable because of
stripped locking technique used in internal implementation of
ConcurrentHashMap class. Unlike Hashtable and Synchronized Map, it never locks
whole Map, instead it divides the map in segments and locking is done on those.
Though it perform better if number of reader threads is greater than number of writer
To be frank, Collections classes are heart of Java API though I feel using them
judiciously is an art. Its my personal experience where I have improved performance
of Java application by using ArrayList where legacy codes were unnecessarily
using Vector etc. Prior Java 5, One of the major drawback of Java Collection
framework was lack of scalability. In multi-threaded Java application synchronized
collection classes like Hashtable and Vector quickly becomes bottleneck; to address
scalability JDK 1.5 introduces some good concurrent collections which is highly
efficient for high volume, low latency system electronic trading systems In general
those are backbone for Concurrent fast access of stored data. In this tutorial we will
look on ConcurrentHashMap, Hashtable, HashMap and synchronized Map and see
difference between ConcurrentHashMap and Hashtable and synchronized Map in Java.
We have already discussed some key difference between HashMap and Hashtable in
Java in this blog and those will also help you to answer this question during

Why need ConcurrentHashMap and

The synchronized collections classes, Hashtable and Vector, and the synchronized
classes, Collections.synchronizedMap() and Collections.synchronizedLi
st(), provide a basic conditionally thread-safe implementation of Map and List.
However, several factors make them unsuitable for use in highly concurrent
applications for example their single collection-wide lock is an impediment to
scalability and it often becomes necessary to lock a collection for a considerable time
during iteration to prevent ConcurrentModificationException.
ConcurrentHashMap and CopyOnWriteArrayList implementations provide much
higher concurrency while preserving thread safety, with some minor compromises in
their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not
necessarily useful everywhere you might use HashMap or ArrayList, but are designed
to optimize specific common situations. Many concurrent applications will benefit
from their use.

Difference between ConcurrentHashMap and Hashtable

So what is the difference between Hashtable and ConcurrentHashMap , both can be
used in multithreaded environment but once the size of Hashtable becomes
considerable large performance degrade because for iteration it has to be locked for
longer duration.
Since ConcurrentHashMap introduced concept of segmentation , how large it becomes
only certain part of it get locked to provide thread safety so many other readers can
still access map without waiting for iteration to complete.
In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable
lock full map while doing iteration. This will be more clear by looking at this diagram
which explains internal working of ConcurrentHashMap in Java.

Difference between ConcurrentHashMap and

ConcurrentHashMap is designed for concurrency and improve performance while
HashMap which is non synchronized by nature can be synchronized by applying a
wrapper using synchronized Map. Here are some of common differences between
ConcurrentHashMap and synchronized map in Java

What is CountDownLatch in Java - Concurrency Example Tutorial

What is CountDownLatch in Java
CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads
before starts processing. This is very crucial requirement and often needed in server side core Java application and
having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java
is introduced on Java 5 along with other concurrent utilities
like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. In
this Java concurrency tutorial we will what is CountDownLatch in Java, How CountDownLatch works in Java, an
example of CountDownLatch in Java and finally some worth noting points about this concurrent utility. You can
also implement same functionality using wait and notify mechanism in Java but it requires lot of code and getting it
write in first attempt is tricky, With CountDownLatch it can be done in just few lines. CountDownLatch also allows
flexibility on number of thread for which main thread should wait, It can wait for one thread or n number of thread,
there is not much change on code. Key point is that you need to figure out where to use CountDownLatch in
Java application which is not difficult if you understand What is CountDownLatch in Java, What
does CountDownLatch do and How CountDownLatch works in Java.

How CountDownLatch works in Java

Now we know What is CountDownLatch in Java, its time to find out How CountDownLatch works in Java.
CountDownLatch works in latch principle, main thread will wait until Gate is open. One thread waits for n number of
threads specified while creating CountDownLatch in Java. Any thread, usually main thread of application, which
callsCountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other
thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready
to the job. as soon as count reaches zero, Thread awaiting starts running. One of the disadvantage
ofCountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any
more, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such

CountDownLatch Exmaple in Java

In this section we will see a full featured real world example of using CountDownLatch in Java. In
following CountDownLatch example, Java program requires 3 services
namely CacheService, AlertService and ValidationService to be started and ready
before application can handle any request and this is achieved by using CountDownLatch in Java.


* Java program to demonstrate How to use CountDownLatch in Java. CountDownLatch is
* useful if you want to start main processing thread once its dependency is completed

* as illustrated in this CountDownLatch Example

* @author Javin Paul
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000,
cacheService.start(); //separate thread will initialize CacheService
alertService.start(); //another thread for AlertService initialization

application should not start processing any thread until all service is up
and ready to do there job.
Countdown latch is idle choice here, main thread will start with count 3
and wait until count reaches zero. each thread once up and read will do
a count down. this will ensure that main thread is not started processing
until all services is up.

//count is 3 since we have 3 Threads (Services)

latch.await(); //main thread is waiting on CountDownLatch to finish
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
* Service class which will be executed by Thread using CountDownLatch synchronizer.
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
public void run() {
try {
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
System.out.println( name + " is Up");
latch.countDown(); //reduce count of CountDownLatch by 1

ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
By looking at output of this CountDownLatch example in Java, you can see that Application is not started until all
services started by individual Threads are completed.

When should we use CountDownLatch in Java :

Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete,
before its start doing processing. Classical example of using CountDownLatch in Java is any server side core
Java application which uses services architecture, where multiple services is provided by multiple threads
and application can not start processing until all services have started successfully as shown in
our CountDownLatch example.

CountDownLatch in Java Things to remember

Few points about Java CountDownLatch which is worth remembering:
1) You can not reuse CountDownLatch once count is reaches to zero, this is the main difference between
CountDownLatch and CyclicBarrier, which is frequently asked in core Java interviews and multi-threading interviews.
2) Main Thread wait on Latch by calling CountDownLatch.await() method while other thread
calls CountDownLatch.countDown() to inform that they have completed.
Thats all on What is CountDownLatch in Java, What does CountDownLatch do in Java,
How CountDownLatch works in Java along with a real life CountDownLatch example in Java. This is a very
useful concurrency utility and if you master when to use CountDownLatch and how to use CountDownLatch you
will be able to reduce good amount of complex concurrency control code written using wait and notify in Java.

What is CyclicBarrier Example in Java 5 Concurrency Tutorial

What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with
other concurrent utility like Counting Semaphore, BlockingQueue, ConcurrentHashMap etc. CyclicBarrier is
similar to CountDownLatch which we have seen in last article What is CountDownLatch in Java and allows
multiple threads to wait for each other (barrier) before proceeding. Difference between CountDownLatch and
CyclicBarrier is a also very popular multi-threading interview question in Java. CyclicBarrier is a natural
requirement for concurrent program because it can be used to perform final part of task once individual tasks are
completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with
number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is
a blocking method in Java and blocks until all Thread or parties call await(). In general calling await() is shout
out that Thread is waiting on barrier. await() is ablocking call but can be timed out or Interrupted by other
thread. In this Java concurrency tutorial we will see What is CyclicBarrier in Java and an example
of CyclicBarrier on which three Threads will wait for each other before proceeding further.
Difference between CountDownLatch and CyclicBarrier in Java
In our last article we have see how CountDownLatch can be used to implement multiple threads waiting for each
other. If you look at CyclicBarrier it also the does the same thing but there is a different you can not
reuse CountDownLatch once count reaches zero while you can reuse CyclicBarrier by
calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is good for
one time event like application start-up time and CyclicBarrier can be used to in case of recurrent event e.g.
concurrently calculating solution of big problem etc. If you like to learn more about threading and concurrency in Java
you can also check my post on When to use Volatile variable in Java and How Synchronization works in Java.

CyclicBarrier in Java Example

Now we know what is CyclicBarrier in Java and it's time to see example of CyclicBarrier in Java. Here is a
simple example of CyclicBarrier in Java on which we initialize CyclicBarrier with 3 parties, means in order to
cross barrier, 3 thread needs to call await() method. each thread calls await method in short duration but they don't
proceed until all 3 threads reached barrier, once all thread reach barrier, barrier gets broker and each thread started
there execution from that point. Its much clear with the output of following example of CyclicBarrier in Java:


* Java program to demonstrate how to use CyclicBarrier in Java. CyclicBarrier is a
* new Concurrency Utility added in Java 5 Concurrent package.
* @author Javin Paul
public class CyclicBarrierExample {
//Runnable task for each thread
private static class Task implements Runnable {
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier) {
this.barrier = barrier;
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
System.out.println(Thread.currentThread().getName() + " has crossed the
} catch (InterruptedException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null,
} catch (BrokenBarrierException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null,

public static void main(String args[]) {

//creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await()
final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
public void run(){
//This task will be executed once all thread reaches barrier
System.out.println("All parties are arrived at barrier, lets play");
//starting each of thread
Thread t1 = new Thread(new Task(cb), "Thread 1");

Thread t2 = new Thread(new Task(cb), "Thread 2");

Thread t3 = new Thread(new Task(cb), "Thread 3");
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All parties are arrived at barrier, lets play
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier

When to use CyclicBarrier in Java

Given the nature of CyclicBarrier it can be very handy to implement map reduce kind of task similar to fork-join
framework of Java 7, where a big task is broker down into smaller pieces and to complete the task you need output
from individual small task e.g. to count population of India you can have 4 threads which counts population from
North, South, East and West and once complete they can wait for each other, When last thread completed there task,
Main thread or any other thread can add result from each zone and print total population. You can
use CyclicBarrier in Java :
1) To implement multi player game which can not begin until all player has joined.
2) Perform lengthy calculation by breaking it into smaller individual tasks, In general to implement Map reduce
Important point of CyclicBarrier in Java
1. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while
creating CyclicBarrier.
2. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
3. Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out.
4. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as
shown below:
at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
5.CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will
terminate with java.util.concurrent.BrokenBarrierException.
That's all on What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to
use CyclicBarrier in Java . We have also seen difference between CountDownLatch and CyclicBarrier in Java
and got some idea where we can use CyclicBarrier in Java Concurrent code.

Why wait, notify and notifyAll is defined in Object Class and not on Thread
class in Java
Why wait, notify and notifyAll is declared in Object Class instead of Thread is famous core java interview
question which is asked during all levels of Java interview ranging from 2 years, 4years to quite senior level position
on java development. Beauty of this question is that it reflect what does interviewee knows about wait notify

mechanism, how does it sees whole wait and notify feature and whether his understanding is not shallow on this
topic. Like Why Multiple inheritance is not supported in Java or why String is final in java there could be
multiple answers of why wait and notify is defined in Object class and every one could justify there reason.

In my all interview experience I found that wait and notify still remains most confusing for most of Java
programmer specially up-to 2 to 3 years and if they asked to write code using wait and notify they often struggle. So if
you are going for any Java interview make sure you have sound knowledge of wait and notify mechanism as well as
you arecomfortable writing code using wait and notify like Produce Consumer problem or implementing Blocking
queue etc. by the way This article is in continuation of my earlier article related to wait and notify e.g. Why Wait and
notify requires to be called from Synchronized block or method and Difference between wait, sleep and yield method
in Java, if you havent read you may found interesting.

Reason Why Wait , Notify and NotifyAll are in Object

Here are some thoughts on why they should not be in Thread class which make sense to me :
1) Wait and notify is not just normal methods or synchronization utility, more than that they are communication
mechanism between two threads in Java. And Object class is correct place to make them available for every
object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and
wait notify are two different area and dont confuse that they are same or related. Synchronized is to provide mutual
exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication
mechanism between two thread.
2 )Locks are made available on per Object basis, which is another reason wait and notify is declared in Object
class rather then Thread class.
3) In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which
threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of
knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and
notify being on object class rather than thread in Java.
These are just my thoughts on why wait and notify method is declared in Object class rather than Thread in
Java and you have different version than me. In reality its another design decision made by Java designer like not
supporting Operator overloading in Java. Anyway please post if you have any other convincing reason why wait and
notify method should be in Object class and not on Thread.

How to avoid deadlock in Java Threads

How to avoid deadlock in Java is one of the question which is flavor of the season for
multithreading , asked more at a senior level and with lots of follow up questions ,
though question looks very basic but most of developer get stuck once you start going
questions starts with "What is deadlock ?"
answer is simple , when two or more threads waiting for each other to
release lock and get stuck for infinite time , situation is called deadlock . it will only
happen in case of multitasking.

How do you detect deadlock in Java ?

though this could have many answers , my version is first I would look the code if I see
nested synchronized block or calling one synchronized method from other or trying to
get lock on different object then there is good chance of deadlock if developer is not
very careful.
other way is to find it when you actually get locked while running the application , try
to take thread dump , in Linux you can do this by command "kill -3" , this will print
status of all the thread in application log file and you can see which thread is locked
on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get
locked and on which object.
once you answer this , they may ask you to write code which will result in
deadlock ?
here is one of my version
public void method1(){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
public void method2(){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
If method1() and method2() both will be called by two or many threads , there is a good
chance of deadlock because if thead 1 aquires lock on Sting object while executing
method1() and thread 2 acquires lock on Integer object while executing method2() both will
be waiting for each other to release lock on Integer and String to proceed further which will
never happen.
now interviewer comes to final part , one of the most important in my view , How to fix
deadlock ? or How to avoid deadlock in Java ?
if you have looked above code carefully you may have figured out that real reason for
deadlock is not multiple threads but the way they access lock , if you provide an ordered
access then problem will be resolved , here is

the fixed version.

public void method1(){

System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
public void method2(){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");

Now there would not be any deadlock because both method is accessing lock on
Integer and String object in same order . so if thread A acquires lock on Integer object
, thread B will not proceed until thread A releases Integer lock , same way thread A
will not be blocked even if thread B holds String lockbecause now thread B will not
expect thread A to release Integer lock to proceed further.

What is Race Condition in multithreading 2 Examples in Java

Race condition in Java is a type of concurrency bug or issue which is introduced in your program because parallel
execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language
hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition
and how to avoid that. Anyway Race conditions are just one of hazards or risk presented by use of multi-threading in
Java just like deadlock in Java. Race conditions occurs when two thread operate on same object without proper
synchronization and there operation interleaves on each other. Classical example of Race condition is incrementing
a counter since increment is not an atomic operation and can be further divided into three steps like read, update and
write. if two threads tries to increment count at same time and if they read same value because of interleaving of read
operation of one thread to update operation of another thread, one count will be lost when one thread overwrite
increment done by other thread. atomic operations are not subject to race conditions because those operation cannot
be interleaved. This is also a popular multi-threading interview questions during core java interviews. In this article
we will see how to find race condition in Java and two sample code patterns which often causes
race conditions in Java.

How to find Race Conditions in Java

Finding Race conditions in any language is most difficult job and Java is no different, though since
readability of Java code is very good and synchronized constructs are well defined heaps to find race conditions by
code review. finding race conditions by unit testing is not reliable due to random nature of race conditions. since
race conditionssurfaces only some time your unit test may passed without facing any race condition. only sure shot
way to find race condition is reviewing code manually or using code review tools which can alert you on potential
race conditions based on code pattern and use of synchronization in Java. I solely rely on code review and yet to find
a suitable tool for exposing race condition in java.

Code Example of Race Condition in Java

Based on my experience in Java synchronization and where we use synchronized keyword I found that two code
patterns namely "check and act" and "read modify write" can suffer race condition if not synchronized properly.
both cases rely on natural assumption that a single line of code will be atomic and execute in one shot which is wrong
e.g. ++ is not atomic.
"Check and Act" race condition pattern
classical example of "check and act" race condition in Java is getInstance() method of Singleton Class,
remember that was one questions which we have discussed on 10 Interview questions on Singleton pattern in Java
as "How to write thread-safe Singleton in Java". getInstace() method first check for whether instance is null and than
initialized the instance and return to caller. Whole purpose of Singleton is that getInstance should always return same
instance of Singleton. if you call getInstance() method from two thread simultaneously its possible that while one
thread is initializing singleton after null check, another thread sees value of _instance reference variable as null (quite
possible in java) especially if your object takes longer time to initialize and enters into critical section which eventually
results in getInstance() returning two separate instance of Singleton. This may not happen always because a fraction
of delay may result in value of _instance updated in main memory. here is a code example
public Singleton getInstance(){
if(_instance == null){ //race condition if two threads sees _instance= null
_instance = new Singleton();
an easy way to fix "check and act" race conditions is to synchronized keyword and enforce locking which will make
this operation atomic and guarantees that block or method will only be executed by one thread and result of operation
will be visible to all threads once synchronized blocks completed or thread exited form synchronized block.
read-modify-update race conditions
This is another code pattern in Java which cause race condition, classical example is the non thread safe counter we
discussed in how to write thread safe class in Java. this is also a very popular multi-threading question where they
ask you to find bugs on concurrent code. read-modify-update pattern also comes due to improper synchronization
of non-atomic operations or combination of two individualatomic operations which is not atomic together e.g. put if
absent scenario. consider below code
here we only insert object into hashtable if its not already there. point is both contains() and put() are atomic but still
this code can result in race condition since both operation together is not atomic. consider thread T1 checks
for conditions and goes inside if block now CPU is switched from T1 to thread T2 which also checks condition and
goes inside if block. now we have two thread inside if block which result in either T1 overwriting T2 value or viceversa based on which thread has CPU for execution. In order to fix this race condition in Java you need to wrap
this code inside synchronized block which makes them atomic together because no thread can go
inside synchronized block if one thread is already there.

These are just some of examples of race conditions in Java, there will be numerous based on your business logic
and code. best approach to find Race conditions is code review but its hard because thinking concurrently is not
natural and we still assume code to run sequentially. Problem can become worse if JVM reorders code in absent of
proper synchronization to gain performance benefit and this usually happens on production under heavily load, which
is worst. I also suggest doing load testing in production like environment which many time helps to expose
race conditions in java. Please share if you have faced any race condition in java projects.

Producer Consumer Design Pattern with Blocking Queue Example in Java

Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between
Producer and Consumer by separating Identification of work with Execution of Work. In producer consumer design
pattern a shared queue is used to control the flow and this separation allows you to code producer and consumer
separately. It also addresses the issue of different timing require to produce item or consuming item. by
using producer consumer pattern both Producer and Consumer Thread can work with different speed. In this article
we will see What is producer consumer problem which is very popular multi-threading interview question, How to
solve producer consumer problem using Blocking Queue and Benefits of using Producer Consumer design pattern.

Real World Example of Producer Consumer Design Pattern

Producer consumer pattern is every where in real life and depict coordination and collaboration. Like
one person is preparing food (Producer) while other one is serving food (Consumer), both will use shared table for
putting food plates and taking food plates. Producer which is the person preparing food will wait if table is full and
Consumer (Person who is serving food) will wait if table is empty. table is a shared object here. On Java
library Executor framework itself implement Producer Consumer design pattern be separating responsibility of
addition and execution of task.

Benefit of Producer Consumer Pattern

Its indeed a useful design pattern and used most commonly while writing multi-threaded or concurrent code. here
is few of its benefit:
1) Producer Consumer Pattern simple development. you can Code Producer and Consumer independently and
Concurrently, they just need to know shared object.
2) Producer doesn't need to know about who is consumer or how many consumers are there. Same is true with
3) Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item.
In fact by monitoring consumer speed one can introduce more consumer for better utilization.
4) Separating producer and Consumer functionality result in more clean, readable and manageable code.

Producer Consumer Problem in Multi-threading

Producer-Consumer Problem is also a popular java interview question where interviewer ask to implement
producer consumer design pattern so that Producer should wait if Queue or bucket is full and Consumer should wait
if queue or

bucket is empty. This problem can be implemented or solved by different ways in Java, classical way is using wait
and notify method to communicate between Producer and Consumer thread and blocking each of them on
individual condition like full queue and empty queue. With introduction of BlockingQueue Data Structure in Java 5 Its
now much simpler because BlockingQueue provides this control implicitly by introducing blocking methods put() and
take(). Now you don't require to use wait and notify to communicate between Producer and Consumer.
BlockingQueue put() method will block if Queue is full in case of Bounded Queue and take() will block if Queue is
empty. In next section we will see a code example of Producer Consumer design pattern.

Using Blocking Queue to implement Producer Consumer

BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox
support of blocking on put() and take(). Developer doesn't need to write confusing and critical piece of wait-notify
code to implement communication. BlockingQuue is an interface and Java 5 provides different implantation
like ArrayBlockingQueue and LinkedBlockingQueue , both implement FIFO order or elements,
while ArrayLinkedQueue is bounded in nature LinkedBlockingQueue is optionally bounded. here is a
complete code example of Producer Consumer pattern with BlockingQueue. Compare it with classic wait
notify code, its much simpler and easy to understand.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerPattern {
public static void main(String args[]){
//Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();
//Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));
//Starting producer and Consumer thread
//Producer Class in java
class Producer implements Runnable {
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
public void run() {
for(int i=0; i<10; i++){
try {

System.out.println("Produced: " + i);

} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
//Consumer Class in Java
class Consumer implements Runnable{
private final BlockingQueue sharedQueue;
public Consumer (BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
public void run() {
try {
System.out.println("Consumed: "+ sharedQueue.take());
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9
You see Producer Thread produced number and Consumer thread consumes it in FIFO order
because blocking queue allows elements to be accessed in FIFO.

Thats all on How to use Blocking Queue to solve Producer Consumer problem or example of Producer
consumer design pattern. I am sure its much better than wait notify example but be prepare with both if you are
going for any Java Interview as Interview may ask you both way.

What is Factory method Design Pattern in Java with Example - Tutorial

Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in
various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java.
Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create
different object from factory often refereed as Item and it encapsulate the creation code. So instead of having
object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of
factory pattern in Java is BorderFactory Class of Swing API. In this Design pattern tutorial we will see What is
Factory method design pattern in Java, What are main advantages of factory pattern in Java , Code example of
Factory design pattern and What problem Factory pattern solves in Java or when to use Factory design
pattern. This article is in continuation of my design pattern article as 10 OOPS and SOLID design principles java
programmer should know and How to use Observer pattern in Java

What is static factory method or factory design pattern

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

Example of static factory method in JDK

Best Example of Factory method design pattern is valueOf() method which is there in String and wrapper classes
like Integer and Boolean and used for type conversion i.e. from converting String to Integer or String to double in
Some more examples of factory method design pattern from JDK is :
valueOf() method which returns object created by factory equivalent to value of parameter passed.
getInstance() method which creates instance of Singleton class.
newInstance() method which is used to create and return new instance from factory method every time called.
getType() and newType() equivalent of getInstance() and newInstance() factory method but used when
factory method resides in separate class.

Problem which is solved by Factory method Pattern in Java

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

Some time our application or framework will not know that what kind of object it has to create at run-time it knows
only the interface or abstract class and as we know we can not create object of interface or abstract class so main
problem is frame work knows when it has to create but dont know what kind of object.
Whenever we create object using new() we violate principle of programming for interface rather than
implementation which eventually result in inflexible code and difficult to change in maintenance. By using Factory
design pattern in Java we get rid of this problem.
Another problem we can face is class needs to contain objects of other classes or class hierarchies within it; this can
be very easily achieved by just using the new keyword and the class constructor. The problem with this approach is
that it is a very hard coded approach to create objects as this creates dependency between the two classes.
So factory pattern solve this problem very easily by model an interface for creating an object which at creation time
can let its subclasses decide which class to instantiate, Factory Pattern promotes loose coupling by eliminating the
need to bind application-specific classes into the code. The factory methods are typically implemented as virtual
methods, so this pattern is also referred to as the Virtual Constructor. These methods create the objects of the
products or target classes.

When to use Factory design pattern in Java

Static Factory methods are common in frameworks where library code needs to create objects of types
which may be sub classed by applications using the framework.

Some or all concrete products can be created in multiple ways, or we want to leave open the option that in
the future there may be new ways to create the concrete product.

Factory method is used when Products don't need to know how they are created.

We can use factory pattern where we have to create an object of any one of sub-classes depending on the
data provided

Code Example of Factory Design Pattern in Java:

Lets see an example of how factory pattern is implemented in Code.We have requirement to create multiple currency
e.g. INR, SGD, USD and code should be extensible to accommodate new Currency as well. Here we have made
Currency as interface and all currency would be concrete implementation of Currency interface. Factory Class will
create Currency based upon country and return concrete implementation which will be stored in interface type. This
makes code dynamic and extensible.
Here is complete code example of Factory pattern in Java:
interface Currency {
String getSymbol();
// Concrete Rupee Class code
class Rupee implements Currency {
public String getSymbol() {
return "Rs";
// Concrete SGD class Code

class SGDDollar implements Currency {

public String getSymbol() {
return "SGD";
// Concrete US Dollar code
class USDollar implements Currency {
public String getSymbol() {
return "USD";
// Factroy Class code
class CurrencyFactory {
public static Currency createCurrency (String country) {
if (country. equalsIgnoreCase ("India")){
return new Rupee();
}else if(country. equalsIgnoreCase ("Singapore")){
return new SGDDollar();
}else if(country. equalsIgnoreCase ("US")){
return new USDollar();
throw new IllegalArgumentException("No such currency");
// Factory client code
public class Factory {
public static void main(String args[]) {
String country = args[0];
Currency rupee = CurrencyFactory.createCurrency(country);

Advantage of Factory method Pattern in Java:

Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In
following are main advantages of using Factory pattern in Java:
1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and
highly cohesive code?
E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used
with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get
Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end
database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS
specific feature?
2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an
object inside factory is more flexible than creating an object directly in the client. Since client is working
on interface level any time you can enhance the implementation and return from Factory.

3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time
object is created using Factory rather than using different constructor at different client side.
4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a
centralized method for object creation and every client is getting object from same place.

Some more advantages of factory method design pattern is:

1. Static factory method used in factory design pattern enforces use of Interface than implementation which itself a
good practice. for example:
Map synchronizedMap = Collections.synchronizedMap(new HashMap());
2. Since static factory method have return type as Interface, it allows you to replace implementation with better
performance version in newer release.
3. Another advantage of static factory method pattern is that they can cache frequently used object
and eliminate duplicate object creation. Boolean.valueOf() method is good example which caches true and false
boolean value.
4. Factory method pattern is also recommended by Joshua Bloch in Effective Java.
5 Factory method pattern offers alternative way of creating object.
6. Factory pattern can also be used to hide information related to creation of object.
Thats all on Factory design patten in Java for now. This is one of the most used patterns in Java library and
different Java frameworks. Summary is try to use Factory pattern whenever you see an opportunity to encapsulate
object creation code and see chance of creating different object in near future.

Observer design Pattern in Java with Real world code Example

Observer design pattern in Java is a fundamental core Java pattern where Observe watch for any
change in state or property of Subject. For Example Company updates all its shareholders for any
decision they make here Company is Subject and Shareholders are Observers, any change in policy of
company and Company notifies all its Shareholders or Observer. This was simple real world
explanation of Observer pattern. In this article we will in detail what is Observer Design pattern, what
is benefit of Observer design Pattern, Example or Observer pattern in Java and few other points. Just
like Decorator design Pattern and Factory Pattern in Java, Observer pattern is also used in JDK.

Observer design Pattern Java Code Example

What is Observer design Pattern?

Observer design pattern in Java is very important pattern and as name suggest its used
to observe things. Suppose you want to notify for change in a particular object than you observer that
object and changes are notified to you. Object which is being observed is refereed as Subject and
classes which observesubject are called Observer. This is beautiful pattern and used heavily along with
Model View Controller Design pattern where change in model is propagated to view so that it can
render it with modified information. Observer pattern is also a very popular Java interview
questions and mostly asked on Senior or mid senior level.

Problem which is solved by Observer Pattern:

If we have requirement that if particular object change its state and on depending upon
This changes some or group of objects automatically change their state we need to implement
observer pattern it will reduce coupling between objects.
In real world if try to find example see when we subscribe for New Phone connection whenever
customer is registered with that company all other departments are notified accordingly and then
depending upon the state the do their jobs like do the verification of their address then if customer
state is verified then dispatch the welcome kit etc.

How Observer Design Pattern is implemented in Java;

For implementation of this pattern java makes our task very easy, developer need not to do so much
for implementing this pattern .In java.util package we can find interfaces ,classes and methods for
implementing this pattern.
Public Interface Observer:
Any class who implements this interface must be notified when subject or observable object change its
Update (Observable Ob, Object arg): This method is called when subject is changed.

Class Observable:
Its a subject to whom observer wants to observe.

Some Important Method:

addObserver(Observer o):add Observers in the set of observers for this subject or observalbel
deleteObserver(Observer o): delete Observers in the set of observers .
hasChanged():check if object has changed.
clearChanged():this method will indicate that subject has no changes or all the observers has been
notified when changes is made.
notifyObservers(): notify all the observers if object has changed .

Code Example of Observer design pattern in Java:

Observer Design pattern is generic than how it is implemented in Java. You are free to
choose java.util.Observable or java.util.Observer or writing your own Subject and Observer interface. I
prefer having my own Subject and Observer interface and this is how I am going to write my Code
Example of Observer design Pattern in java. Mine Example is very Simple you have a Loan on which
interest rate is subject to change and when it changes, Loan notifies to Newspaper or Internet media

to display new loan interest rate. To implement this we have a Subject interface which contains
methods for adding, removing and notifying Observers and an Observer interface which
contains update(int interest) method which will be called by Subject implementation when interest
rate changes.
import java.util.ArrayList;
interface Observer {
public void update(float interest);
interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObservers();
class Loan implements Subject {
private ArrayList<Observer> observers = new ArrayList<Observer>();
private String type;
private float interest;
private String bank;
public Loan(String type, float interest, String bank) {
this.type = type;
this.interest = interest;
this.bank = bank;
public float getInterest() {
return interest;
public void setInterest(float interest) {
this.interest = interest;
public String getBank() {
return this.bank;
public String getType() {
return this.type;
public void registerObserver(Observer observer) {
public void removeObserver(Observer observer) {

public void notifyObservers() {
for (Observer ob : observers) {
.println("Notifying Observers on change in Loan
interest rate");
class Newspaper implements Observer {
public void update(float interest) {
System.out.println("Newspaper: Interest Rate updated, new Rate is: "
+ interest);
class Internet implements Observer {
public void update(float interest) {
System.out.println("Internet: Interest Rate updated, new Rate is: "
+ interest);
public class ObserverTest {
public static void main(String args[]) {
// this will maintain all loans information
Newspaper printMedia = new Newspaper();
Internet onlineMedia = new Internet();
Loan personalLoan = new Loan("Personal Loan", 12.5f,
"Standard Charterd");
Advantage of Observer Design Pattern in Java:
Main advantage is loose coupling between objects called observer and observable. The subject only
know the list of observers it dont care about how they have their implementation.All the observers
are notified by subject in a single event call as Broadcast communication
Disadvantage of Observer Design Pattern in Java:

The disadvantage is that the sometime if any problem comes, debugging becomes very difficult
because flow of control is implicitly between observers and observable we can predict that now
observer is going to fire and if there is chain between observers then debugging become more

Another issue is Memory management because subject will hold all the reference of all the observers
if we not unregister the object it can create the memory issue.
Thats all on Observer Pattern in Java. Share your thought how and when you have used Observer
Pattern in your Project and any issue you have faced?

How to write Thread-Safe Code in Java

thread-safety or thread-safe code in Java refers to code which can safely be used or shared in
concurrent or multi-threading environment and they will behave as expected. any code, class or object
which can behave differently from its contract on concurrent environment is not thread-safe. threadsafety is one ofthe risk introduced by using threads in Java and I have seen java programmers
and developers struggling to write thread-safe code or just understanding what is threadsafe code and what is not? This will not be very detailed article on thread-safety or low level details
of synchronization in Java instead we will keep it simple and focus on one example of non threadsafe code and try to understand what is thread-safety and how to make an code thread-safe.

How to make Thread-Safe Code in Java

Example of Non Thread Safe Code in Java

Here is an example of non thread-safe code, look at the code and find out why this code is
not thread safe ?
* Non Thread-Safe Class in Java
public class Counter {
private int count;

* This method is not thread-safe because ++ is not an atomic operation
public int getCount(){
return count++;

Above example is not thread-safe because ++ (increment operator) is not an atomic

operation and can be broken down into read, update and write operation. if multiple thread
call getCount() approximately same time each of these three operation may coincide or overlap with
each other for example while thread 1 is updating value , thread 2 reads and still gets old value, which
eventually let thread 2 override thread 1 increment and one count is lost because multiple thread
called it concurrently.

How to make code Thread-Safe in Java

There are multiple ways to make this code thread safe in Java:

1) Use synchronized keyword in Java and lock the getCount() method so that only one thread can
execute it at a time which removes possibility of coinciding or interleaving.
2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are
thread-safe and saves cost of external synchronization.

here is a thread-safe version of Counter class in Java:

* Thread-Safe Example in Java
public class Counter {
private int count;
AtomicInteger atomicCount = new AtomicInteger( 0 );

* This method thread-safe now because of locking and synchornization
public synchronized int getCount(){
return count++;

* This method is thread-safe because count is incremented atomically
public int getCountAtomically(){
return atomicCount.incrementAndGet();

Important points about Thread-Safety in Java

Here is some points worth remembering to write thread safe code in Java, these knowledge also
helps you to avoid some serious concurrency issues in Java like race condition or deadlock in Java:
1) Immutable objects are by default thread-safe because there state can not be modified once
created. Since String is immutable in Java, its inherently thread-safe.
2) Read only or final variables in Java are also thread-safe in Java.
3) Locking is one way of achieving thread-safety in Java.
4) Static variables if not synchronized properly becomes major cause of thread-safety issues.
5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.
6) Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an
atomic operation it can't interleave with other thread.
7) local variables are also thread-safe because each thread has there own copy and using local
variables is good way to writing thread-safe code in Java.

8) In order to avoid thread-safety issue minimize sharing of objects between multiple thread.
9) Volatile keyword in Java can also be used to instruct thread not to cache variables and read from
main memory and can also instruct JVM not to reorder or optimize code from threading perspective.

Thats all on how to write thread safe class or code in Java and avoid serious concurrency issues
in Java. To be frank thread-safety is a little tricky concept to grasp, you need to think concurrently in
order to catch whether a code is thread-safe or not. Also JVM plays a spoiler since it can reorder
code for optimization, so the code which looks sequential and runs fine in
development environment not guaranteed to run similarly in production environment because JVM
may ergonomically adjust itself as server JVM and perform more optimization and reorder which
cause thread-safety issues.

How to debug java program in Eclipse

Debugging is a must have skill for any java developer. Having ability to debug java
program enables to find you any subtle bug which is not visible during code review or comes when a
particular condition offer, This becomes even more important if you are working in high frequency
trading or electronic trading system project where time to fix a bug is very less and bug usually comes
on production environment and doesn't appear in your Windows XP machine. in my experience
debugging java application also helps you understand flow of java program. In this java tutorial we will
see how to debug a java program, setting up remote debugging in java and some java debugging tips
on Eclipse and Netbeans IDE. Its also good to know various java debug tool available and how java
debugger or jdb works but its not mandatory for doing debugging in Java. To start java
debugging you just needs your project to be configured in a modern IDE like eclipse and Netbeans
and you are ready to debug java program.

Java debugging tools

I mostly used Eclipse IDE and Netbeans IDE for java development and these IDE have great
support for java debugging. They allow you to set various breakpoints like line breakpoint,
conditional breakpoints or exception breakpoint. I prefer Eclipse over netbeans because of its
seamless integration with remote debugging because most of the time your applicationwill run on
Linux machine and you might not have local version running on your machine, in such scenario remote
debugging is extremely useful. You can check how to setup java remote debugging in eclipse for step
by step guide on setting remote debugging in eclipses. Apart from Eclipse and Netbeans IDE you can
also use Java debugger jdb which is a simple command line based java debugger and based on java
platform debugging architecture and can be used to debug java program locally or remotely.

Java debug options

If you are not using any IDE for java debugging locally you need to provide java debug option while
starting your program. You need to provide java debug option also if you are setting up remote

debugging session or using jdb for java debugging. Following are the two java debugging option which
needs to be provided to java program:
Debug Options

Used to run java program in

debug mode


Loads in Process debugging

libraries and specifies the
kind of connection to be
Suspend=y and n is quite useful for debugging from start or debugging at any point.

Using jdb to debug java application

1) Start your java program with two options provided above for example, below command will start
StockTrading java program in debug mode.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
After starting your java application in debug mode you can attach java debugger "jdb" to the VM with
the following command:
% jdb -attach 8000
You can check the jdb manual page for complete detail on how to do java debugging with jdb.

Java remote debugging with eclipse

This is another cool feature of eclipse which allows you to connect your java application running on
remote host and do remote debugging. You just need to start your java application with the java
debug option discussed above and then connect your application from eclipse into specified port. You
can check below link for step by step guide on java remote debugging with eclipse.

Debugging Java Program in Eclipse and Netbeans

Debugging java application locally on any IDE like Eclipse or Netbeans its very simple, just select the
project and click debug or use debug shortcut provided by IDE. You can also debug a single java class
with main method. In Eclipse just right click and select "Debug as Java Application".

10 practical Java debugging tips

Now let's see some java debugging tips which I used while doing debugging in Java in eclipse.
1) Use conditional breakpoint
Eclipse allows you to setup conditional break point for debugging java program, which is a breakpoint
with condition and your thread will only stop at specified line if condition matches instead of just
stopping on that line like in case of line breakpoint. To setup a conditional breakpoint just double click
on any line where you want to setup a breakpoint and then right click --> properties and then insert
the condition. Now program will only stop when that particular condition is true and program is
running on debug mode.

2) Use Exception breakpoint

How many times you have frustrated with a NullPointerException and you don't know the source from
where the exception is coming. Exception breakpoints are just made for such situation. Both Eclipse
and Netbeans allows you to setup Exception breakpoint. You can setup Exception breakpoint based on
java exception like NullPointerException or ArrayIndexOutOfBoundException. You can setup Exception
breakpoint from breakpoint window and your program will stop when you start it on debug mode and
exception occurs.

3) Step over, Step Into

These are simply great debugging options available in any Java IDE, extremely useful if you are
debugging multi-threaded application and want to navigate step by step.
4) Stopping for a particular Thread
This is my own custom made java debugging tips which I made using conditional breakpoints. since
most of my projects are multi-threaded java programs and I want only a particular thread to stop on a
particular line, for doing that I setup a conditional breakpoint on that line and
put Thread.currentThread().getName().equals("TestingThread") and it works fantastically.
5) Inspect and Watch
These are two menu options which I use to see the value of expression during debugging java
program. I just select the statement, right click and inspect and it will show you the value of that
statement at debugging time. You can also put watch on that and that condition and its value will
appear on watch window.
6) Suspending and resuming thread
You can suspend and resume any thread while debugging java program from debug window. Just right
click on any thread and select either suspends or resume. This is also very useful while debugging
multi-threading program and simulating race conditions.
7) Using logical structure
Logical structure option is very useful for examining contents inside java collection classes like java
hasmap or Java Arraylist during java debugging. Logical view will show the contents like key and value
of hashmap instead of showing full details of hashmap which we may not be interested, you can
enable and disable logical view from variables window.
8) Step filtering
When we do Step Into on process debugging java program control goes form one class to other and it
eventually go to JDK classes like System or String. Some time we just to remain in our application and
don't want to navigate into JDK System classes in that case Step filtering is great you can just filter
out JDK class from Step into. You can setup step filtering from preferences JavaDebugStep
Filtering and enable and disable it from Debug window.
9) Copy Stack
While debugging java program if you want to copy the stack of a thread which hit the breakpoint and
suspended you do so by "Copy Stack" option. Just right click on Thread on Debug Window
and select "Copy Stack".
10) Last tip is use java debugging as last option and not the first option because its very time
consuming, especially remote java debugging which takes a lot of time if network latency is very high
between local and remote host. Try to identify problem by looking at code it would be very handy and
lastly java debugging is real fun so definitely try it few times to get hold of it and please share some
other java debugging tips you use on your daily life.

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview
and interview is not said completed until they will not cover the Collection Framework and multithreading interview and collections are uncompleted without Covering Hash Set and Hash Map.
Both HashMap and HashSet are part of collection framework which allows us to work with collection of
objects. Collection Framework has their own interfaces and implementation classes. Basically
collection is divided as Set Interface, List and Queue Interfaces. All this interfaces have their own
property also apart from they get from collection like Set allows Collection of objects but
forbids duplicate value, List allows duplicate along with indexing.Queue woks on FCFS algorithm.
First we have one look on What HashMap and Hashset is then will go for Differences between
HashSet and HashMap
What is HashSet in Java?

HashSet is implementation of Set Interface which does not allow duplicate value all the
methods which are in Collection Framework are also in Set Interface by default but when we are
talking about Hash set the main thing is objects which are going to be stored in HashSet
must override equals() andhashCode() method so that we can check for equality and
no duplicate value are stored in our set.if we have created our own objects we need to
implement hashCode() and equal() in such a manner that will be able to compare
objects correctly when storing in a set so that duplicate objects are not stored,if we have not override
this method objects will take default implementation of this method.

public boolean add(Object o) Method is used to add element in a set which returns false if its
a duplicate value in case of HashSet otherwise returns true if added successfully.

What is HashMap?

HashMap is a implementation of Map Interface, which maps a key to value.Duplicate keys are not
allowed in a map.Basically map Interface has two implementation classes HashMap and TreeMap the
main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null
values and nullkeys.HashMap is not synchronized,but collection framework provide methods so that
we can make them synchronized if multiple threads are going to access our hashmap and one thread
is structurally change our map.
public Object put(Object Key,Object value) method is used to add element in map.

You can read more about HashMap in my article How HashMap works in Java and Difference between
HashMap and hashtable in Java

Difference between HashSet and HashMap in Java

Following are some differences between HashMap and Hashset:

Hash Map
HashMap is a implementation of Map
HashMap Stores data in form of key
value pair
Put method is used to add element in
In hash map hashcode value is
calculated using key object

HashMap is faster than hashset

because unique key is used to access

Hash Set
HashSet is an implementation of Set
HashSet Store only objects
Add method is used to add element is
Here member object is used
forcalculating hashcode value which
can be same for two objects so equal
() methodis used to check for equality
if it returns false that means two
objects are different.
HashSet is slower than Hashmap

Please let me know if you need any other difference between HashSet and HashMap in Java and I will
add them here

Why String is Immutable or Final in Java

String is Immutable in Java because String objects are cached in String pool. Since
cached String literal is shared between multiple client there is always a risk, where
one client's action would affect all other client. For example, if one client changes
value of String "Test" to "TEST", all other client will also see that value as explained in
first example. Since caching of String objects was important from performance reason
this risk was avoided by making String class Immutable. At the same time, String was
made final so that no one can compromise invariant of String class e.g. Immutability,
Caching, hascode calculation etc by extending and overriding behaviors. Another
reason of why String class is immutable could de due to HashMap. Since Strings are
very popular as HashMap key, it's important for them to be immutable so that they
can retrieve the value object which was stored in HashMap. Since HashMap works
in principle of hashing, which requires same has value to function properly. Mutable
String would produce two different hashcode at the time of insertion and retrieval
if contents of String was modified after insertion, potentially losing the value object
in map. If you are an Indian cricket fan, you may be able to correlate with my next
sentence. String is VVS Laxman of Java, i.e. very very special class. I have not seen a
single Java program which is written without using String. That's why solid
understanding of String is very important for a Java developer. Important and

popularity of String as data type, transfer object and mediator has also make it
popular on Java interviews. Why String is immutable in Java is one of the most
frequently asked String Interview questions in Java, which starts with discussion of,
What is String, How String in Java is different than String in C and C++, and then
shifted towards what is immutable object in Java , what are the benefits of
immutable object, why do you use them and which scenarios should you use them.
This question some time also asked as "Why String is final in Java". e

Why String is Final in Java

As I said, there could be many possible answer of this question, and only designer
of String class can answer it with confidence, I think following two reasons make a lot
of sense on why String class is made Immutable or final in Java : 1) Imagine String
pool facility without making string immutable , its not possible at all because in case
of string pool one string object/literal e.g. "Test" has referenced by many reference
variables , so if any one of them change the value others will be automatically gets
affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into
"TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many Java classes e.g. for opening
network connection, you can pass hostname and port number as string , you can pass
database URL as string for opening database connection, you can open any file in
Java by passing name of file as argument to File I/O classes.
In case, if String is not immutable, this would lead serious security threat , I mean
some one can access to any file for which he has authorization, and then can change
the file name either deliberately or accidentally and gain access of those file.
Because of immutability, you don't need to worry about those kind of threats. This
reason also gel with, Why String is final in Java, by
making java.lang.String final, Java designer ensured that no one overrides any
behavior of String class.
3)Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming and to avoid any synchronization issues in
Java, Immutability also makes String instance thread-safe in Java, means you don't
need to synchronize String operation externally. Another important point to note
about String is memory leak caused by SubString, which is not a thread related issues
but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its
hashcode , being immutable String in Java caches its hashcode, and do not calculate
every time we call hashcode method of String, which makes it very fast as hashmap
key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in
comments below. In short because String is immutable, no one can change
its contents once created which guarantees hashCode of String to be same on multiple
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh
Johnsson on comments is: The absolutely most important reason that String is
immutable is that it is used by the class loading mechanism, and thus have profound
and fundamental security aspects. Had String been mutable, a request to load
"java.io.Writer" could have been changed to load
Security and String pool being primary reason of making String immutable, I believe
there could be some more very convincing reasons as well, Please post those reasons
as comments and I will include those on this post. By the way, above reason holds
good to answer, another Java interview questions "Why String is final in Java". Also
to be immutable you have to be final, so that your subclass doesn't break

Java Synchronization Tutorial : What, How and Why?

Multit-hreading and synchronization is a very important topic for any Java
programmer. Good knowledge of multithreading, synchronization, and
thread-safety can put you in front of other developers, at same time it's not
easy to master these concept. In fact writing correct concurrent code is one
of the hardest thing, even in Java, which has several inbuilt synchronization
utilities. In this Java synchronization tutorial we will learn what is meaning of
Synchronization in Java, Why do we need Synchronization in Java, What is
java synchronized keyword, examples of using Java
synchronized method and blocks, What can happen in multithreading
code in absence of synchronized constructs, tips to avoid mistakes, while
locking critical section in Java and some of important points about
synchronization in Java. Since Java provides different constructs to provide
synchronization and locking e.g. volatile keyword, atomic variable, explicitly
locking using java.util.concurrent.lock.Lock interface and there popular
implementations e.g.ReentrantLock and ReentrantReadWriteLock, It
becomes even more important to understand difference between
synchronized and other constructs. Remember, clear understanding of
synchronization is must to write correct concurrent code in Java, which is free
of multithreading issues like deadlock, race conditions and thread-safety. I
am sure, things learned in this Java synchronization tutorial will help.
Once you gone through this article, You can further read Java Concurrency in

Practice to develop your concept. That's the one of those book which every
Java developer must read.

What is Synchronization in Java

Synchronization in Java is an important concept since Java is a multithreaded language where multiple threads run in parallel to complete
program execution. In multi-threaded environment synchronization of Java
object or synchronization of Java class becomes extremely important.
Synchronization in Java is possible by using Java
keywords "synchronized" and "volatile. Concurrent access of shared
objects in Java introduces to kind of errors: thread interference and memory
consistency errors and to avoid these errors you need to properly
synchronize your Java object to allow mutual exclusive access of critical
section to two threads. By the way This Java Synchronization tutorial is in
continuation of my article How HashMap works in Java and difference
between HashMap and Hashtable in Java if you havent read already you
may find some useful information based on my experience in Java

Why do we need Synchronization in Java?

If your code is executing in multi-threaded environment, you
need synchronization for objects, which are shared among multiple threads,
to avoid any corruption of state or any kind of unexpected behavior.
Synchronization in Java will only be needed if shared object is mutable. if
your shared object is either read only or immutable object, than you don't
need synchronization, despite running multiple threads. Same is true with
what threads are doing with object if all the threads are only reading value
then you don't require synchronization in Java. JVM guarantees that Java
synchronized code will only be executed by one thread at a time. In
Summary Java synchronized Keyword provides following functionality
essential for concurrent programming :
1) synchronized keyword in Java provides locking, which ensures mutual
exclusive access of shared resource and prevent data race.
2) synchronized keyword also prevent reordering of code statement by
compiler which can cause subtle concurrent issue if we don't
use synchronized or volatile keyword.

3) synchronized keyword involve locking and unlocking. before entering

into synchronized method or block thread needs to acquire the lock, at
this point it reads data from main memory than cache and when it release
the lock, it flushes write operation into main memory which eliminates
memory inconsistency errors.

Synchronized keyword in Java

Prior to Java
1.5 synchronized keyword was only way to provide synchronization of
shared object in Java. Any code written by using synchronized block or
enclosed inside synchronized method will be mutually exclusive, and can
only be executed by one thread at a time. You can have both static
synchronized method and non static synchronized method and
synchronized blocks in Java but we can not have synchronized variable in
java. Using synchronized keyword with variable is illegal and will result in
compilation error. Instead of synchronized variable in Java, you can have
java volatile variable, which will instruct JVM threads to read value of
volatile variable from main memory and dont cache it locally. Block
synchronization in Java is preferred over method synchronization in
Java because by using block synchronization, you only need to lock the
critical section of code instead of whole method. Since synchronization in
Java comes with cost of performance, we need to synchronize only part of
code which absolutely needs to be synchronized.

Example of Synchronized Method in Java

Using synchronized keyword along with method is easy just apply
synchronized keyword in front of method. What we need to take care is that
static synchronized method locked on class object lock and non static
synchronized method locks on current object (this). So its possible that
both static and non static java synchronized method running in parallel. This
is the common mistake a naive developer do while writing Java
synchronized code.

public class Counter{

private static int count = 0;
public static synchronized int getCount(){
return count;
public synchoronized setCount(int count){
this.count = count;
In this example of Java synchronization code is not properly
synchronized because both getCount() and setCount() are not getting
locked on same object and can run in parallel which may results in incorrect
count. Here getCount() will lock in Counter.class object
while setCount() will lock on current object (this). To make this code
properly synchronized in Java you need to either make both method static or
non static or use java synchronized block instead of java
synchronized method.By the way this is one of the common mistake Java
developers make while synchronizing their code.

Example of Synchronized Block in Java

Using synchronized block in java is also similar to using synchronized
keyword in methods. Only important thing to note here is that if object
used to lock synchronized block of code, Singleton.class in below example
is null then Java synchronized block will throw a NullPointerException.
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
if(_instance == null)
_instance = new Singleton();

return _instance;
This is a classic example of double checked locking in Singleton. In
this example of Java synchronized code, we have made only critical
section (part of code which is creating instance of singleton) synchronized
and saved some performance. If you make whole method synchronized than
every call of thismethod will be blocked, while you only need blocking to
create singleton instance on first call. By the way, this is not the only way to
write threadsafe singleton in Java. You can use Enum, or lazy loading to avoid
thread-safety issue during instantiation. Even above code will not behave as
expected because prior to Java 1.5, double checked locking was broker and
even with volatile variable you can view half initialized object. Introduction of
Java memory model and happens before guarantee in Java 5 solves this
issue. To read more about Singleton in Java see that.

Important points of synchronized keyword in Java

1. Synchronized keyword in Java is

used to provide mutual exclusive access of a shared resource with multiple
threads in Java. Synchronization in Java guarantees that, no two threads can
execute a synchronized method which requires same lock simultaneously or
2. You can use java synchronized keyword only on synchronized method or
synchronized block.
3. When ever a thread enters into java synchronized method or block
it acquires a lock and whenever it leaves java synchronized method or
block it releases the lock. Lock is released even if thread
leaves synchronized method after completion or due to any Error or
4. Java Thread acquires an object level lock when it enters into an instance
synchronized java method and acquires a class level lock when it enters into
static synchronized java method.

5. Java synchronized keyword is re-entrant in nature it means if a java

synchronized method calls another synchronized method which requires
same lock then current thread which is holding lock can enter into that
method without acquiring lock.
6. Java Synchronization will throw NullPointerException if object used in java
synchronized block is null e.g. synchronized (myInstance) will
throws java.lang.NullPointerException if myInstance is null.
7. One Major disadvantage of Java synchronized keyword is that it
doesn't allow concurrent read, which can potentially limit scalability. By using
concept of lock stripping and using different locks for reading and writing,
you can overcome this limitation of synchronized in Java. You will be glad to
that java.util.concurrent.locks.ReentrantReadWriteLock provides
ready made implementation of ReadWriteLock in Java.
8. One more limitation of java synchronized keyword is that it can only
be used to control access of shared object within the same JVM. If you have
more than one JVM and need to synchronized access to a shared file system
or database, the Java synchronized keyword is not at all sufficient. You need
to implement a kind of global lock for that.
9. Java synchronized keyword incurs performance cost. Synchronized
method in Java is very slow and can degrade performance. So use
synchronization in java when it absolutely requires and consider using java
synchronized block for synchronizing critical section only.
10. Java synchronized block is better than java synchronized
method in Java because by using synchronized block you can only lock
critical section of code and avoid locking whole method which can possibly
degrade performance. A good example of java synchronization around this
concept isgetInstance() method Singleton class. See here.
11. Its possible that both static synchronized and non static synchronized
method can run simultaneously or concurrently because they lock on
different object.
12. From java 5 after change in Java memory model reads and writes are
atomic for all variables declared using volatile keyword (including
long and double variables) and simple atomic variable access is more
efficient instead of accessing these variables via synchronized java code. But
it requires more care and attention from the programmer to avoid memory
consistency errors.

13. Java synchronized code could result in deadlock or

starvation while accessing by multiple thread if synchronization is not
implemented correctly. To know how to avoid deadlock in java see here.
14. According to the Java language specification you can not use Java
synchronized keyword with constructor its illegal and result in
compilation error. So you can not synchronized constructor in Java which
seems logical because other threads cannot see the object being created
until the thread creating it has finished it.
15. You cannot apply java synchronized keyword with variables and
can not use java volatile keyword with method.
16. Java.util.concurrent.locks extends capability provided by java
synchronized keyword for writing more sophisticated programs since they
offer more capabilities e.g. Reentrancy and interruptible locks.
17. Java synchronized keyword also synchronizes memory. In fact java
synchronized synchronizes the whole of thread memory with main memory.
18. Important method related to synchronization in Java
are wait(), notify() and notifyAll() which is defined in Object class. Do
you know, why they are defined in java.lang.object class instead
of java.lang.Thread? You can find some reasons, which make sense.
19. Do not synchronize on non final field on synchronized block in
Java. because reference of non final field may change any time and then
different thread might synchronizing on different objects i.e. no
synchronization at all. example of synchronizing on non final field :
private String lock = new String("lock");
System.out.println("locking on :" + lock);

any if you write synchronized code like above in java you may get
warning "Synchronization on non-final field" in IDE like Netbeans and
20. Its not recommended to use String object as lock in java
synchronized block because string is immutable object and literal string
and interned string gets stored in String pool. so by any chance if any other
part of code or any third party library used same String as there lock then
they both will be locked on same object despite being completely unrelated
which could result in unexpected behavior and bad performance. instead of

String object its advised to use new Object() for Synchronization in Java
on synchronized block.
private static final String LOCK = "lock";
//not recommended
private static final Object OBJ_LOCK = new Object(); //better
public void process() {
synchronized(LOCK) {

21. From Java library Calendar and SimpleDateFormat classes are not threadsafe and requires external synchronization in Java to be used in multithreaded environment.
Probably most important point about Synchronization in Java is that, in the
absence of synchronized keyword or other construct e.g. volatile variable or
atomic variable, compiler, JVM and hardware are free to make optimization,
assumption, reordering or caching of code and data, which can cause subtle
concurrency bugs in code. By introducing synchronization by using volatile,
atomic variable or synchronized keyword, we instruct compiler and JVM to
not to do that.
Update 1: Recently I have been reading several Java Synchronization and
Concurrency articles in internet and I come across jeremymanson's blog
which works in google and has worked on JSR 133 Java Memory Model, I
would recommend some of this blog post for every java developer, he has
covered certain details about concurrent programming , synchronization and
volatility in simple and easy to understand language, here is the
link atomicity, visibility and ordering.
Update 2: I am grateful to my readers, who has left some insightful
comments on this post. They have shared lots of good information and
experience and to provide them more exposure, I am including some of there
comments on main article, to benefit new readers.
@Vikas wrote
Good comprehensive article about synchronized keyword in Java. to be
honest I have never read all these details about synchronized block or
method at one place. you may want to highlight some limitation of
synchronized keyword in Java which is addressed by explicit locking using
new concurrent package and Lock interface :
1. synchronized keyword doesn't allow separate locks for reading and
writing. as we know that multiple thread can read without affecting thread-

safety of class, synchronized keyword suffer performance due to contention

in case of multiple reader and one or few writer.
2. if one thread is waiting for lock then there is no way to time out, thread
can wait indefinitely for lock.
3. on similar note if thread is waiting for lock to acquired there is no way to
interrupt the thread.
All these limitation of synchronized keyword is addressed and resolved by
using ReadWriteLock and ReentrantLock in Java 5.
@George wrote
Just my 2 cents on your great list of Java Synchronization facts and best
practices :
1) synchronized keyword in internally implemented using two byte code
instructions MonitorEnter and MonitorExit, this is generated by compiler.
Compiler also ensures that there must be a MonitorExit for every
MonitorEnter in different code path e.g. normal execution and abrupt
execution, because of Exception.
2) java.util.concurrent package different locking mechanism than
provided by synchronized keyword, they mostly used ReentrantLock, which
internally use CAS operations, volatile variables and atomic variables to get
better performance.
3) With synchronized keyword, you have to leave the lock, once you exist a
synchronized method or block, there is no way you can take the lock to other
method. java.util.concurrent.locks.ReentrantLock solves this problem
by providing control for acquiring and releasing lock, which means you can
acquire lock in method A and can release in method B, if they both needs to
be locked in same object lock. Though this could be risky as compiler will
neither check nor warn you about any accidental leak of locks. Which means,
this can potentially block other threads, which are waiting for same lock.
4) Prefer ReentrantLock over synchronized keyword, it provides more
control on lock acquisition, lock release and better performance compared to
synchronized keyword.
5) Any thread trying to acquire lock using synchronized method will block
indefinitely, until lock is available. Instead this, tryLock() method
of java.util.concurrent.locks.ReentrantLock will not block if lock is not
Having said that, I must say, lots of good information.

Recommend Books to learn Synchronization and Concurrency in Java

Synchronization and Concurrency is complex topic in Java and it's not easy to master
them. Even more experienced Java developers struggle to write correct concurrent
code in Java. I would highly recommend following Java books to master multithreading, synchronization and Concurrency.
1. Java Concurrency in Practice By Brian Goeatz and team
2. Effective Java by Joshua Bloach
3. Java Threads By Scott Oaks and Henry Wong