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.

will static keywords tell one per JVM in Java ?

It is very good question during interview
so it wrong to say that static keyword say One per JVM , bcz class can be loaded in more than one classloader. And thus, static fields are not per-VM (as you might initially conclude), but per-classloader. Working in an app server or plugin environment using post-delegation classloaders, this comes up a lot

Chain of responsibility Design pattern Concept with Example

Chain Of Responsibility Pattern creates a chain of objects that examine a request. Each object in turn examines the request and handles it if it can, otherwise passes it on to the next object in the chain. So each object in the chain acts as a handler.

The object that ultimately handles the request is unknown explicitly to the sender object that sends the request. By this way we are using chain of responsibility pattern to decouple the sender of the request and its receivers.

Each object on the chain shares a common interface for handling requests and for accessing its successor on the chain.

Receipt is not guaranteed - a request could fall off the end of the chain without being handled.

The Java Servlet filter framework is an example of chain of resposibility design. Note that the chain.doFilter() is the method that should be called to make the chain roll. If the subclass missed it, the whole chain would be stopped or blocked.

Java exception handling is another example of chain of responsibility design. When an error occurs, the exception call will look for a handling class. If there is no handler, the super Exception class will be called to throw the exception. Otherwise, the handler class will handle it. Processing stops after an event is handled.

Chain of responsibility simplifies object interconnections.Instead of senders and receivers maintaining references to all candidate receivers,each sender keeps a single reference to the head of the chain,and each receiver keeps a single reference to the immediate successor in the chain.

Chain Of Responsibility uses Command Pattern to represent requests as objects
Chain of Responsibility is often applied in conjunction with CompositePattern.There,a component's parent act as its successor.

package cop;

abstract class Car {
 
 public double price = 5.5;
 public String color = "Silver";
 public String size = "Small";
 
 
 // The Next Element in the Chain of Responsibility
 protected Car next; 
 
 protected Car searchNext(Car car) { 
  next=car; 
  return this;
 } 
 
 public void trail(String performance) {
  if(price < 10 && performance.equalsIgnoreCase("Satisfactory")){   
   buyCar(performance);
  }
  else{
   if(next!=null)
    next.trail(performance);
  }
 }  
 
 abstract protected void buyCar(String performance);
}





package cop;

public class Innova extends Car{
 
 public Innova(double price,String color,String size) {
  this.price = price;
  this.color = color;
  this.size = size;
 }
 
 protected void buyCar(String performance) {
  System.out.println("Liked Innova ...  performance... "+performance);
 }
}





package cop;

public class Toyota extends Car{
 
 public Toyota(double price,String color,String size) {
  this.price = price;
  this.color = color;
  this.size = size;
 }
 
 protected void buyCar(String performance) {
  System.out.println(" Liked Toyota ... performance... "+performance);
 }
}





package cop;

public class SearchCars {

 public static void main(String[] args) {
  Car car=new Toyota(10.5,"black","big").searchNext(new Innova(8.5,"silver","medium"));
  car.trail("Satisfactory"); 
 }

}




When To Use:
1. Use Chain Of Responsibility Pattern when you want to give more than one object a chance to handle a request and the actual handler is not known in advance.
2. Commonly used in windows systems to handle events like mouse clicks and keyboard events.
3. When you want to avoid coupling the sender of a request to its receiver.

Advantages:
1. Decouples the sender of the request and its receivers.
2. Simplifies your object as it doesn't have to know about the chain structure and keep direct references to its members.
3. Allows you to add or remove responsibilities dynamically by changing the members or order of the chain.


Disadvantage:
1. Hard to observe the runtime characteristics and debug.

Java classloader concept | bootstrap , system, user classloader in java

The Class loader concept, one of the cornerstones of the Java virtual machine, describes the behavior of converting a named class into the bits responsible for implementing that class. Because class loaders exist, the Java run time does not need to know anything about files and file systems when running Java programs.

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.

When a new JVM instance is started , the bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file. We cannot find the details of the bootstrap class loader in the java language specification, since this is a native implementation. For this reason the behavior of the bootstrap class loader will differ across JVMs.

Java can change its class storage model simply by changing the set of functions that implements the class loader.

Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader.

ex : Bootstrap (primordial) Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) and is the parent in the Class loaders hierarchy.

next comes the Extensions (Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE) and then System (Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options) ClassLoaders.

Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendants (ie Extensions and Systems class loaders).

The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).

If there were any sibling class loaders they cannot see classes loaded by each other. They can only see the classes loaded by their parent class loader. For example Sibling1 class loader cannot see classes loaded by
Sibling2 class loader

Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap)


Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true


Note : Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:

Class r = loadClass(String className, boolean resolveIt);

The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well).

We can build our own ClassLoader by being a subclass of java.lang.ClassLoader. The only abstract method that must be implemented is loadClass().

Static Class Loading :

Classes are statically loaded with Java’s 'new' operator.


class MyClass {
 public static void main(String args[]) {
  Car c = new Car();
 }
}




A NoClassDefFoundException is thrown if a class is referenced with Java’s 'new' operator (i.e. static loading) but the runtime system cannot find the referenced class.

Dynamic class loading:

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.

we can load classes dynamically by...


Class.forName (String className); //static method which returns a Class



The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.



class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object).
Jeep myJeep = null ;

//myClassName should be read from a properties file or Constants interface.

//stay away from hard coding values in your program.
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);



A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:
1. The forName(..) method in class - Class.
2. The findSystemClass(..) method in class - ClassLoader.
3. The loadClass(..) method in class - ClassLoader.

The Java virtual machine has hooks in it to allow a user-defined class loader to be used in place of the primordial one. Furthermore, since the user class loader gets first crack at the class name, the user is able to implement any number of interesting class repositories, not the least of which is HTTP servers -- which got Java off the ground in the first place.

There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files).

How to create Proxy object in java | creation of proxy object concept in spring AOP

J2SE v1.3 has introduced a dynamic proxy class in the Java Reflection package.
A dynamic proxy class implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.
 Proxy classes and instances are created using static methods of the java.lang.reflect.Proxy class.Each proxy class has one public constructor that takes one argument, an implementation of the java.lang.reflect.InvocationHandler interface.


package com.prox;

public interface Showable {
   
public void show();
}





-------------------------------------


package com.prox;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyHandler implements InvocationHandler{
   
    Showable target;
    public  MyHandler(Showable target)
    {
        this.target=target;
    }
    public Object invoke(Object proxy, Method m, Object [] args)throws Throwable
    {
        Object o= m.invoke(target, args);
        return o;
    }

}


------------------------------------------

package com.prox;

public class A implements Showable{
   
    public void show()
    {
       
        System.out.println("Inside the Class A");
    }

}


---------------------------------------------


package com.prox;


import java.lang.reflect.Proxy;

public class ProxyTest {
   
    public static void main(String [] args)
    {
       
        System.out.println("Inside the main method");
        A  target = new  A();
        B  target1 = new  B();
        MyHandler handler= new MyHandler(target1);
        try {
         System.out.println("creating Proxy object");
         Showable pr=(Showable)Proxy.newProxyInstance(B.class.getClassLoader(),new
                Class[]{Showable.class}, handler);
       
        System.out.println("The Invoking show method on proxy object");
        pr.show();
        System.out.println("the proxy object"+pr.getClass().getName());
        //B b=(B)pr;
        //b.notShow();
        }
       
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

}


-------------------------------------------

In above code we have created a proxy object concept

Drawback of proxy object

  • One limitation is that the method must be called through an instance of the proxy class. So nested methods calls, for instance, would not be intercepted.
  • Another limitation is that the method must have been defined in an Interface that is implemented by the object being proxied. It can not be called through an instance of a class that does not implement an interface.

can we override init(ServletConfig config) method in servlet class in J2ee ?

Yes , we can override init(ServletConfig config) into servlet , but when you retrive ServletCofig object into inside servlet give Nullpointer Exception .

Code:
package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class servlettest extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
   
    public void init(ServletConfig config) throws ServletException
    {
    }
/**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("first_name");
        System.out.println("The name is"+name);
        try {
         ServletConfig config=getServletConfig();
        System.out.println("The get Servlet config is"+config.getServletContext());
        System.out.println("The servlet name is"+config.getServletName());
        }
        catch(Exception ex)
        {
            System.out.println("The exception is"+ex);
        }
        RequestDispatcher rd= request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);
       
    //    super.doGet(request, response);
    }

   

}


OUTPT:

The name is
The exception isjava.lang.NullPointerException



In above code it will clear that Servlet container intstantiate servlet and give server and enviornment information to particular servlet
through init(ServletConfig config) . 

Can we give constructor with arguments in servlet in Java ?

Ans- No, we cannot give a constructor with arguments in servlet in java because servlet container responsible for creating servlet instance so it call no arguments constructor in servley if you give constructor with arguments then it will give error at time of instantiating

 Incorrect Way

package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class servlettest
 */
public class servlettest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */

    public servlettest(int a) {
       System.out.println("Inside the constructor"+a);
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("first_name");
        System.out.println("The name is"+name);
       
        RequestDispatcher rd= request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);
    //    super.doGet(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
 
Error will give at time of instantiating
javax.servlet.ServletException: Error instantiating servlet class com.servlet.servlettest org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:870) org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:685) java.lang.Thread.run(Thread.java:595)