Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday, 13 July 2013

How many way we can break Singleton Class in java | Singleton design concept in java

Singleton Pattern ensures a class has only one instance and provides a global point of access to it.

The default constructor of the class is made private, which prevents the direct instantiation of the object by other classes.

A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance(){
  if(instance == null)
      instance = new BookingFactory();
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



In future if you get a requirement for having more than one instance then singleton allows multiple instances without affecting a singleton class's clients. Just you need to do is make a small change in Singleton Class, which doesn't effect the client's code.

Note that the singleton instance is only created when needed. This is called lazy instantiation.


public class SingletonDemo {
 
 public static void main(String args[]) {
   
 // Get a reference to the single instance of Singleton.
 BookingFactory bookingFactory = BookingFactory.getInstance();
 
 // Set the data value.
 bookingFactory.setData(34);
 
 System.out.println("First reference: " + bookingFactory);
 System.out.println("Singleton data value is: " +bookingFactory.getData());
 }
 
}



How can we break Singleton:

1. It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle.

Solution :

In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration.

Make the Instance access method Synchronized to prevent concurrent thread access.



public static synchronized BookingFactory getInstance()




Synchronization is expensive, however, and is really only needed the first time the unique instance is created.

Do an eager instantiation of the instance rather than a lazy instantiation.

You can also instantiate the Singleton as soon as the class loads. i.e You can place it in static block to ensure that it happens only once.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 static {
  instance = new BookingFactory();
 }
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance()
 {
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



Instead of synchronizing the whole method you can also make the instance variable as static final. It is thread-safe because static member variables created when declared are guaranteed to be created the first time they are accessed. You get a thread-safe implementation that automatically employs lazy instantiation.



public class BookingFactory {

   private final static BookingFactory instance = new BookingFactory();

   private BookingFactory() {
         // Exists only to defeat instantiation.
      }
}




But you loose the flexibility of having more than one instance in future without changing client's code.



2. if you are using multiple classloaders, this could defeat the Singleton implementation and result in multiple instances.

Solution:

Because multiple classloaders are commonly used in many situations—including servlet containers—you can wind up with multiple singleton instances no
matter how carefully you've implemented your singleton classes. If you want to make sure the same classloader loads your singletons, you must specify the
classloader yourself; for example:


private static Class getClass(String classname)
                                         throws ClassNotFoundException {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      if(classLoader == null)
         classLoader = Singleton.class.getClassLoader();
      return (classLoader.loadClass(classname));
   }
}



The preceding method tries to associate the classloader with the current thread; if that classloader is null, the method uses the same classloader that loaded a singleton base class. The preceding method can be used instead of Class.forName().



3. If SingletonClass implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

Solution:

To avoid the above you need to implement readResolve() method.


private Object readResolve() {
    return INSTANCE;
}



The previous singleton implementation returns the lone singleton instance from the readResolve() method; therefore, whenever the Singleton class is deserialized, it will return the same singleton instance.


4. We will be able to create a copy of the Object by cloning it using the Object’s clone method.

Solution:

Override the Object clone method to prevent cloning

This can be done as shown below


SingletonDemo clonedObject = (SingletonDemo) obj.clone();



This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.


public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}



When to use:
We can use this while creating objects of thread pools, caches etc to avoid wasting resources.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...