Thursday, November 28, 2013

Integer constant pool in java

In this post, we'll look into Integer Wrapper class and its Integer constant pool concept with reason behind it for creating such pool with few examples.

What is Integer Class?
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

Before moving further please guess the output of the following program. If you are able to answer them all correct, then it's means you know how Java Integer Constant pool works :)

You can find the answer at the bottom of the post. If your answers are not right, then read further to know why Integer class behave in a unusual way.

Integer i = 10 vs Integer j = new Integer(10)
After compiling this class, I tried to de-compile the same class. What is got it this
So java called Integer.valueOf() whenever we create object of Integer class as Integer i = 10;

Integer.valueOf()
Let's see what does this function do. As per the Oracle doc, it says 
public static Integer valueOf(int i)
Returns an Integer instance representing the specified int value. 

If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

To explore further, let's have a look at the code of Integer.valueOf() function 

It's clear from the above code that when we call valueof() function with value range from -128 to 127, it always cache the value.



Integer.cache is the class that help us in caching in Integer values. The size of the cache may be controlled by the 
-XX:AutoBoxCacheMax= <size>
Or this can achieved with system property
-Djava.lang.Integer.IntegerCache.high=<size>

In other words, when we create object of Integer class 
Integer i = 10;
Integer j = new Integer(10); 
both refer to the same instance in the pool.
So you get the same reference if value is between -128 to 127 and you call valueOf() else it just returns new Integer(int). As reference is same your == operator works for integer returned by valueOf() between this range.

Java caches the integer objects in the range -128 to 127. So, when you try to assign a value in this range to a wrapper object, the boxing operation will invoke Integer.valueOf() method and in turn it will assign a reference to the object already in the pool.
On the other hand, if you assign a value outside this range to a wrapper reference type, Integer.valueOf will create a new Integer object for that value. And hence, comparing the reference for Integer objects having value outside this range will give you false.

I hope at this point, you got the idea of Integer Constant pool. So have a look at the above code for which you have to guess the output and see this time, will you able to answer all the question correct.

Summary of Integer constant pool


Answers
IntegerClassExampleOne 
i==j is not equal

IntegerClassExampleTwo
i==j is not equal

IntegerClassExampleThree
i==j is not equal

IntegerClassExampleFour
i==j is equal



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, November 24, 2013

Object equality, hashCode() vs equals() in Java

In this post, we'll see what makes two object equals and when to override equals() and hashCode() method. Also we'll see what is difference between Reference equality and Object Equality.

Let's first see what does Object class methods equals() and hashCode() says.
equals()
hashCode()

Overriding equals()
This is what Object equals() method look like.
public boolean equals(Object obj) {
        return (this == obj);
}
It simply using the == operator to compare.
Comparing two object references using the == operator evaluates to true only when both references refer to the same object because == simply looks at the bits in the variable, and they're either identical or they're not.

Let's see an example to understand this. 

public class ReferenceDemo {  
  public static void main(String[] javalatte) {  
  Dog d1 = new Dog("DogA");  
  Dog d2 = new Dog("DogA");  
  if(d1.equals(d2)){  
   System.out.println("Dog's are equal");  
  }else {  
   System.out.println("Dog's are not equal");  
  }  
  Dog d = new Dog("Tommy");  
  Dog tommy1 = d;  
  Dog tommy2 = d;  
  if(tommy1.equals(tommy2)){  
   System.out.println("Dog's are equal");  
  }else {  
   System.out.println("Dog's are not equal");  
  }  
  }  
 }  
 class Dog{  
  private String name;  
  Dog(String title){  
  this.name=title;  
  }  
  public String getTitle(){  
  return name;  
  }  
 }  
Sample Output
Dog's are not equal
Dog's are equal
Now it clear why we got this output because equals method looks at the bits in the variable, and they're either identical or they're not.

If you see the String class and the wrapper classes have overridden the equals() method (inherited from class Object), so that you could compare two different objects (of the same type) to see if their contents are meaningfully equivalent. If two different String instances both hold the String value "javalatte", as far as you're concerned they are equal. The fact that the value "javalatte lives in two separate objects doesn't matter.

String class overridden equals() method code
public boolean equals(Object anObject) {
     if (this == anObject) {
         return true;
     }
     if (anObject instanceof String) {
         String anotherString = (String)anObject;
         int n = count;
         if (n == anotherString.count) {
             char v1[] = value;
             char v2[] = anotherString.value;
             int i = offset;
             int j = anotherString.offset;
             while (n-- != 0) {
                 if (v1[i++] != v2[j++])
                     return false;
             }
             return true;
         }
     }
     return false;
 }
To clear this picture, let's see an another example and have a look on the output
 public class StringReferenceDemo {  
  public static void main(String[] java) {  
  String s1 = new String("javalatte");  
  String s2 = new String("javalatte");  
  if(s1.equals(s2)){  
   System.out.println("String's are equal");  
  }else{  
   System.out.println("String's are not equal");  
  }  
  }  
 }  
Sample Output
String's are equal
If you see the "javalatte" string live in separate object, but they are equal because String class has overridden the equals() method.

When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals() method. For each class you write, you must decide if it makes sense to consider two different instances equal. For some classes, you might decide that two objects can never be equal. For example, imagine a class Car that has instance variables for things like make, model, year, configuration—you certainly don't want your car suddenly to be treated as the very same car as someone with a car that has identical attributes.
Your car is your car and you don't want your neighbor Pardeep driving off in it just because, "hey, it's really the same car; the equals() method said so".So no two cars should ever be considered exactly equal.
If two references refer to  one car, then you know that both are talking about one car, not two cars that have the same attributes. So in the case of a Car you might not ever need, or want, to override the equals() method.

What It Means If You Don't Override equals()
If you don't override a class's equals() method, you won't be able to use those objects as a key in a hashtable and you probably won't get accurate Sets, such that there are no conceptual duplicates.
The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.
As you have seen in the "ReferenceDemo" class where
Dog d1 =  new Dog("DogA");
Dog d2 =  new Dog("DogA");
di and d2 are not equal

Let's look at what it means to not be able to use an object as a hashtable key.
Imagine you have a Dog, a very specific car that you want to put in a HashMap, so that you can search on a particular Dog and retrieve the corresponding Person object that represents the owner. So you add the Dog instance as the key to the HashMap. But now what happens when you want to do a search? You want to say to the HashMap collection, "Here's the Dog, now give me the Person object that goes with this Dog." But now you're in trouble unless you still have a reference to the exact object you used as the key when you added it to the Collection. In other words, you can't make an identical Car object and use it for the search.
The bottom line is this: if you want objects of your class to be used as keys for a hashtable (or as elements in any data structure that uses equivalency for searching for—and/or retrieving—an object), then you must override equals() so that two different instances can be considered the same.

Understanding Hashcodes
Imagine a set of buckets lined up on the floor. Someone hands you a piece of paper with a name on it. You take the name and calculate an integer code from it by using A is 1, B is 2, and so on, and adding the numeric values of all the letters in the name together. A given name will always result in the same code;

We don't introduce anything random, we simply have an algorithm that will always run the same way given a specific input, so the output will always be identical for any two identical inputs. So far so good? Now the way you use that code is to determine which bucket to place the piece of paper into.Now imagine that someone comes up and shows you a name and says, "Please retrieve the piece of paper that matches this name." So you look at the name they show you, and run the same hashcode-generating algorithm. The hashcode tells you in which bucket you should look to find the name.
You might have noticed a little flaw in our system, though. Two different names might result in the same value. For example, the names Amy and May have the same letters, so the hashcode will be identical for both names. That's acceptable, but it does mean that when someone asks you  for the Amy piece of paper, you'll still have to search through the target bucket reading each name until we find Amy rather than May. The hashcode tells you only which bucket to go into, but not how to locate the name once we're in that bucket.

How some of the collections use hashcodes
The above distributed-across-the-buckets example is similar to the way hashcodes are used in collections. When you put an object in a collection that uses hashcodes, the collection uses the hashcode of the object to decide in which bucket/slot the object should land. Then when you want to fetch that object you have to give the collection a reference to an object that the collection compares to the objects it holds in the collection. As long as the object you're trying to search for has the same hashcode as the object you're using for the search then the object will be found.

But…and this is a Big One, imagine what would happen if, going back to our name example, you showed the bucket-worker a name and they calculated the code based on only half the letters in the name instead of all of them. They'd never find the name in the bucket because they wouldn't be looking in the correct bucket!
Now can you see why if two objects are considered equal, their hashcodes must also be equal? Otherwise, you'd never be able to find the object since the default hashcode method in class Object virtually always comes up with a unique number for each object, even if the equals() method is overridden in such a way that two or more objects are considered equal

What makes two object equal?
First, we have to ask - what makes two Dog references duplicate? They must be considered equal. Is it simply two references to the very same object, or it is two different object both have the same title?
This  brings up a key issue : reference equality vs object equality

Reference equality






if ( tommy == jakky ) {
// both references referring to the same object on the heap
}








Two references, one object on the heap.
Two references that refer to the same object on the heap are equal. If you call the hashCode() method on the both references, you will get the same result. If you don't override the hashCode() method, the default behavior is that each object will get a unique number.

If you want to know if the 2 references are really referring to the same object, use the == operator, which compares the bits in the variable. If both references point to the same objects, the bits will be identical. 


Object equality




if(tommy.equals(jakky) && tommy.hashCode() == jakky.hashCode() ){
// both references are referring to either a single object, or to tow objects that are equal
}








Two references, two objects on the heap, but the objects are considered meaningfully equivalent.
If you want to treat two different Dog objects as equal ( for example if you have decided that 2 Dog are the same if have matching name), you must override both the hashCode() and equals() method inherited from Object.

As I said above, if you don't override the hashCode() method, the default behavior is to give each object a unique hashcode value. So you must override hashCode() to be sure that two equivalent objects return the same hashcode. But you must also override equals() so that if you call it on either object passing in the other object, always return true.


How HashSet checks for duplicates : hashCode() and equals()
When you put an object into a HashSet, it uses the object's hashcode value to determine where to put the object in the Set. But it also compares the object's hashcode to the hashcode of all the objects in the HashSet, and if there is no matching hashcode, the HashSet assume that this new object is not a duplicate.
In other words, if the hashcodes are different, the HashSet assumes there is no way the objects can be equal.
So you must override hashCode() to make sure the object have the same value.
But two objects with the same hashCode() might not be equals, so if the HashSet finds a matching hashcode for two objects - one you are inserting and one already in the set -  the HashSet will then call one of the object's equals() methods to see if there hashcode matched object are really equals.
And if they are equal, the HashSet knows that the objects you are attempting to add is duplicate of something in the Set, so the add doesn't happen.

Let's see an example of HashSet for checking how it check for duplicate in the HashSet


import java.util.HashSet;  
 public class HashCodeDemo {  
  public static void main(String[] args) {  
  HashSet<Cat> hm = new HashSet<Cat>();  
  Cat c1 = new Cat("abc");  
  Cat c2 = new Cat("abcd");  
  Cat c3 = new Cat("xyz");  
  System.out.println("Adding c1");  
  System.out.println(hm.add(c1));  
  System.out.println("Adding c2");  
  System.out.println(hm.add(c2));  
  System.out.println("Adding c3");  
  System.out.println(hm.add(c3));  
  }  
 }  
 class Cat{  
  private String name;  
  Cat(String title){  
  this.name=title;  
  }  
  public String getName(){  
  return name;  
  }  
  public boolean equals(Object obj){  
  System.out.println("equals is called");  
  Cat c = (Cat)obj;  
  return name.equals(c.getName());  
  }  
  public int hashCode(){  
  System.out.println("hashcode is called");  
  return name.length();  
  }  
 }  
Sample Output
Adding c1
hashcode is called
true
Adding c2
hashcode is called
true
Adding c3
hashcode is called
equals is called
true

It's clear from the output that when it try to add c3 element in the hashSet it first called hashCode() to compare the hashcode value and on finding the same value it called equals() to check whether they are really equals or not.





If you know anyone who has started learning java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Friday, November 15, 2013

User defined Exception in java

In this post, we'll see how to defined custom exceptions in java. We'll also see an example of user defined exception that elaborate more detail or how it is helpful in giving user friendly message to the user.




Java has built-in support for exceptions. 
The Java language supports exception handling in the form of following keywords

  • throw
  • throws
  • try
  • catch
  • finally




In most situations or cases, it will be sufficient to throws exception that are already provided in the Java library. For example, if you’re checking for the validity of the arguments passed to a public function, and you find them to be null or out of expected range, you can throw an IllegalArgumentException. 
However, for most non-trivial applications, it will be necessary for you to develop your own exception classes (custom exceptions) to indicate exceptional conditions.

Basic Exception hierarchy 


The basic syntax of exception handling-related keywords


How do you define a custom exception?

There are two options: you can extend

  • Exception
  • RuntimeException

If you want to force the users of your custom exception to handle the exception, then you can extend your exception class from the Exception class, which will make your custom exception a checked exception.

If you want to give flexibility to the users of your custom exception, and leave it to the users of your exception to decide if they want to handle the exception or not, you can derive your exception from the RuntimeException class.

So it is a design choice that you make to choose the base class of your custom exception.

How about extending the Throwable or Error class for custom exceptions?

  • The Throwable class is too generic to make it the base class of your exception, so it is not recommended.
  • The Error class is reserved for fatal exceptions that the JVM can throw (such as StackOverflowError), so it is not advisable to make this the base class of your exception



For extending from a base class, you need to see what methods the base class provides.
In this case, you want to create a custom exception by extending the Exception or RuntimeException classes. Since the Exception class is the base class of the RuntimeException class, it is sufficient to know the members of the Exception class.


Member Short description
Exception() Default constructor of the Exception class with no additional
information on the exception.
Exception(String) Constructor that takes a detailed information string about the constructor as
an argument.
Exception(String, Throwable) In addition to a detailed information string as an argument, this exception
constructor takes the cause of the exception (which is another exception) as
an argument.
Exception(Throwable) Constructor that takes the cause of the exception as an argument
String getMessage() Returns the detailed message
Throwable getCause() Returns the cause of the exception
Throwable[] getSuppressed() Returns the list of suppressed exceptions as an array.
void printStackTrace() Prints the stack trace (i.e., the list of method calls with relevant line
numbers) to the console (standard error stream). If the cause of an
exception (which is another exception object) is available in the exception,then that information will also be printed. Further, if there are any suppressed exceptions, they are also printed.



For illustrating how to create your own exception classes,we'll create a custom exception InvalidUserInputException.

Sample Output
Type an integer on the console
asdsa
Wrapping exception and throwing
Exception is of type:InvalidUserInputException: Invalid integer value entered
Original caught exception is of type java.util.InputMismatchException


In this InvalidUserInputException class, you did not introduce any new fields but you can add any fields if necessary. This is also a simple custom exception where the constructors simply call the base class versions of the same constructor type.

In this code, we use InvalidUserInputException just like any other exception already defined in the Java library. You are catching the InvalidUserInputException thrown from the readIntFromConsole() method in the main() method.
Since the cause of InvalidUserInputException is InputMismatchException, this exception name is printed in the console as a fully qualified name, java.util.InputMismatchException. You can think of InputMismatchException causing InvalidUserInputException; these two exceptions are known as chained exceptions.


One point to remember is here that as we have extended RuntimeException we are giving flexibility to the users of your custom exception, and leave it to the users of your exception to decide if they want to handle the exception or no.

I want you to try to create the same exception class by extending Exception class and see how it differ from the above exception .


Unchecked Exceptions — The Controversy
Why java does recommend to specify or throw Unchecked exception?
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Friday, November 8, 2013

Singleton in Java

Everybody knows what's Singleton class and Singleton Pattern, but here we see different approaches with detailed examples and where we use this pattern in general scenario. If you know what is a Singleton, I want you to go through this article once as this give you a detailed overview of singleton class in Java.


Singleton pattern



"The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time."

This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.







You use the Singleton pattern to satisfy four simultaneous requirements:
  • An application must have EXACTLY ONE instance of a particular class.
  • The only instance must be accessible to client from a well-known access point.
  • The sole instance should be extensible by subclassing.
  • Clients must be able to use and extend the instance without modifying their own code.







Implementation
In order to write a singleton class, you'll need to understand the following:
  • Implementation of a singleton pattern must satisfy the single instance and global access principles.
  • It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects
  • The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object.
  • To make sure that the object cannot be instantiated any other way, the constructor is made private
  • The singleton pattern must be carefully constructed in multi-threaded applications.


Let see how we are going to make a singleton class:
  • Creating a static variable of the instance of your singleton class will ensure that there are no two instances created at any given point.
  • Exposing a method named getInstance() will return the instance of the class: either by creating it or returning the instance if it already exists.
  • Singletons class constructor is declared as private so that the class could not be initialized from outside.

package Singleton;
public class LazySingleton {
 private static LazySingleton instance;
 /*
  * Prevent instantiaton from other clasess
  */
 private LazySingleton(){  
 }
 public  static LazySingleton getInstance(){
  if(instance==null){
   instance = new LazySingleton();   
  }
  return instance;
 }
}
package Singleton;
public class LazySingletonDemo {
 public static void main(String[] javalatte) {
  for(int i=0;i<10;i++){
   System.out.println(LazySingleton.getInstance());
  }
 }
}
Sample Output
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32
Singleton.LazySingleton@372f2b32

Singleton.LazySingleton@372f2b32

You can see from the above output that same instance is returned.

lazy initialization
The above code implements the concept of lazy initialization — meaning, you are creating the object of the singleton class, only when the getInstance() method is invoked. It also means that if the getInstance() method is not invoked, then the instance shall never be created

To implement the same LazySingleton in multi-threaded environment, you need to use the synchronized keyword.

package Singleton;
public class LazySingletonSynchronized {
 private static LazySingletonSynchronized instance;
 /*
  * Prevent instantiaton from other clasess
  */
 private LazySingletonSynchronized(){  
 }
 public  static synchronized LazySingletonSynchronized getInstance(){
  if(instance==null){
   instance = new LazySingletonSynchronized();   
  }
  return instance;
 }
}
Using the synchronized keyword in this way will be extremely costly, because it's acted upon every time the getInstance() method is invoked. There is a different technique to avoid performance bottlenecks in applications, and this is to modify the code to synchronize only the assignment in the getInstance() method
package Singleton;
public class LazySingletonSynchronized1 {
 private static LazySingletonSynchronized1 instance;
 /*
  * Prevent instantiaton from other clasess
  */
 private LazySingletonSynchronized1(){  
 }
 public  static  LazySingletonSynchronized1 getInstance(){
  if(instance==null){
   synchronized(LazySingletonSynchronized1.class){
    if(instance==null){
     instance = new LazySingletonSynchronized1();
    }
   }
  }
  return instance;
 }
}

This above code method uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs.

Well, this implementation is also not a foolproof solution for a multi-threaded application. It creates a problem due to erroneous out-of-order writes allowed by the Java memory model. Although the memory model problem was reportedly fixed in Java 5, we do not encourage you to use this solution.
The above solution can be made thread-safe in another way with the concept of eager instantiation

Eager initialization
If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance
package Singleton;
public class EagerSingleton {
 private static final EagerSingleton instance =  new EagerSingleton();
 private EagerSingleton(){  
 }
 public static EagerSingleton getInstance(){
  return instance;
 }
}
This method has a number of advantages:
  • The instance is not constructed until the class is used.
  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

Static block initialization
This approch allowing some pre-processing (e.g. for error-checking). In this sense, the traditional approach could be seen as a particular case of this one, as the class loader would do exactly the same processing
package Singleton;
public class StaticSingleton {
 private static final StaticSingleton instance;
 static{
  try{
   instance = new StaticSingleton();
  }catch(Exception ex){
   throw new RuntimeException("oh, an error occurred!", ex);
  }
 }
 private StaticSingleton(){
 }
 public static StaticSingleton getInstance(){
  return instance;
 }
}

Demand holder idiom
"Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. 
The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. 
It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
package Singleton;
public class DemandHolderSingleton {
 private DemandHolderSingleton(){  
 }
 /*
  * SingletonHolder is loaded on the first execution of Singleton.getInstance()
  * or the first access to SingletonHolder.INSTANCE, not before.
  */
 public static class SingletonHolder{
  public static final DemandHolderSingleton instance = new DemandHolderSingleton();
 } 
 public static DemandHolderSingleton getInstance(){
  return SingletonHolder.instance;
 }
}
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

How it works
The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM).
When the class DemandHolderSingleton s loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. 
The static class definition SingletonHolder within it is not initialized until the JVM determines that SingletonHolder must be executed. The static class SingletonHolder is only executed when the static method getInstance is invoked on the class DemandHolderSingleton   and the first time this happens the JVM will load and initialize the LazyHolder class. 
The initialization of the SingletonHolder  class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class  DemandHolderSingleton .

When to use it
Use this pattern if the initialization of the class is expensive and it cannot be done safely at class-loading time and the initialization is concurrent. The crux of the pattern is the safe removal of the synchronization overhead associated with accessing a singleton instance

When not to use it
Avoid this idiom if the construction of INSTANCE can fail. If construction of INSTANCE fails, an invocation of Something.getInstance() will result in a java.lang.ExceptionInInitializerError error. Handling, or mishandling, of these types of construction initialization failures is a common criticism of this idiom and the singleton pattern in general.

The Enum way
In the second edition of his book Effective Java, Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects.


public enum EnumSingleton {
 INSTANCE;
}
OR
public enum EnumSingleton {
 INSTANCE;
 public static EnumSingleton getInstance(){
  return INSTANCE;
 }
}


Final example, that demonstrate Logger class:
package Singleton;
public class Logger {
 private Logger(){  
 }
 public static class Holder{
  public static final Logger instance = new Logger();
 }
 public static Logger getIntance(){
  return Holder.instance;
 }
 public void log(String s){
  System.err.println(s);
 }
}
package Singleton;
public class LoggerDemo {
 public static void main(String[] args) {
  Logger logger = Logger.getIntance();
  logger.log("Hello, I'm logger instance");
 }
}

Applicability & Examples
According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:
  1. Logger Classes
    The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.
  2. Configuration Classes
    The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.
  3. Accesing resources in shared mode
    It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.
  4. Factories implemented as Singletons
    Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.



Related Post
Best Way to synchronized primitive datatypes in java
How Thread works in phases
How Threads exchanges data
Class Loader concept in detail


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...