How to implement Singleton

Answer Posted / manoj kumar

public class DateUtil implements Serializable,Cloneable {

   private static volatile Dateutil instance;

   private DateUtil() {
     //no-op
   }

   public static DateUtil getInstance() {

      if(instance==null) {
        synchronized(DateUtil.this) {
           if(instance==null) {
              instance = new DateUtil();
           }
        }
        return instance;
      }
   
   protected Object readResolve() {
     return instance;
   }

   public Object clone() throws CloneNotSupportedException {

     super.clone();

     throw new CloneNotSupportedException;
  }

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Can we override private methods?

538


What is static variable with example?

551


Explain wrapper classes in java?

524


Is singleton thread safe in java?

540


What do you mean by constructor?

540






What is java literals?

572


Is a boolean variable?

511


What are the various access specifiers in java?

559


How will you compute size of a structure?

574


What are java packages? What's the significance of packages?

617


Can we override data members in java?

617


What is concurrent hashmap and its features?

513


What is the difference between length and length () in java?

523


what is use of functional interface in java 8?

552


What is volatile data type?

549