Creating a thread-safe singleton class

The best way is:

public class ExampleSingleton {
  private static ExampleSingleton instance;
  public static ExampleSingleton getInstance() {
    if( instance == null ) {
      synchronized( ExampleSingleton.class ) {
        if ( instance == null ) {
           instance = new ExampleSingleton();
      }//sync ends
    return instance;

to make it threadsafe you have to use synchronization. But if you sync the whole method, you will create a tiny unnecessary performance overhead. Watch that the second if-condition is vitally important. Lets say instance is null, at this point two threads are executing the method. one thread goes in the sync block and the other starts waiting. when the second thread gets the lock and enters sync block, the Singleton has already been creates by the first thread. If you ommit the second if-condition, the second thread will create a second instance of the singleton.

Hope it helps.