This post look on how applications components typically interact. Event-based programming, also called event-driven architecture (EDA) is an architectural style in which one or more components in a software system execute in response to receiving one or more event notifications.

 

1. Request-response interactions

Client formulate a request, It is sent across the internet to a web server. Client wait while the server constructs a response. This response is returned across the internet to client.

 

image

In a synchronous interaction the provider is expected to send a response back

image

 

2. Events and the principle of decoupling

Events are sometimes used to represent changes of state. The system being monitored is represented as a set of resources each of which is associated with state information. Event producers send events then internal state values change. This allows monitoring applications to be notified immediately when something happens, without their having to continually poll all the resources.

In a decoupled event processing system an event producer does not depend on a particular processing or course of action being taken by an event consumer. Moreover, an event consumer does not depend on processing performed by the producer other than the production of the event itself.

 

Above chart shows Decoupling of Entities from Object-Orientation to Event-Driven Architecture.

 

3. Push-style event interactions
 
In here events are often sent as one-way messages. It pushes the event to each consumer as a one-way message as below diagram. Event producer wait for a response from the consumer

image

 

4.  Channel-based event distribution

In 3 model, producer has to send multiple copies of the same event to consumers. The event producer can find their identities by consulting an external information source.

image

 

5. Request-response interactions to distribute events

In pull-style distribution, the consumer uses the standard request-response pattern to request an event from a producer, or from an intermediary channel.To avoid having to hold on to events and to avoid having to service requests from multiple consumers, event consumer 1 sending a pull request directly to the event producer (message 1).
producer uses a regular push (message 3) to send the event to the channel, and consumer 2 requests it (message 3.1) from the channel. This approach can be extended to send multiple events in
the response messages.

image

Where is this useful

  • A consumer that is only available occasionally
  • A producer that is unable to distribute events
  • A consumer that is physically unable to receive unsolicited incoming events(eg: due to firewall)
  • A consumer that wants to regulate its processing of events and have control
    over exactly when it receives them
0

Add a comment

We used have  Singleton Design Pattern in our applications whenever it is needed. As we know that in singleton design pattern we can create only one instance and can access in the whole application. But in some cases, it will break the singleton behavior.

There are mainly 3 concepts which can break singleton property of a singleton class in java. In this post, we will discuss how it can break and how to prevent those.

Here is sample Singleton class and SingletonTest class.

Singleton.Java

package demo1;

public final class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

SingletonTest.java


package demo1;

public class SingletonTest {
    public static void main(String[] args) {
        Singleton object1 = Singleton.getInstance();
        Singleton object2 = Singleton.getInstance();
        System.out.println("Hashcode of Object 1 - " + object1.hashCode());
        System.out.println("Hashcode of Object 2 - " + object2.hashCode());
    }
}

Here is output, you can see it the same hashcode for objectOne and objectTwo

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 1836019240

Now we will break this pattern. First, we will use java reflection.

Reflection

Java  Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime. Using Reflection API we can create multiple objects in singleton class. Consider the following example.

ReflectionSingleton.java

package demo1;

import java.lang.reflect.Constructor;

public class ReflectionSingleton {
    public static void main(String[] args)  {

        Singleton objOne = Singleton.getInstance();
        Singleton objTwo = null;
        try {
            Constructor constructor = Singleton.class.getDeclaredConstructor();
            constructor.setAccessible(true);
            objTwo = (Singleton) constructor.newInstance();
        } catch (Exception ex) {
            System.out.println(ex);
        }

        System.out.println("Hashcode of Object 1 - "+objOne.hashCode());
        System.out.println("Hashcode of Object 2 - "+objTwo.hashCode());

    }
}

Example to show how reflection can break the singleton pattern with Java reflect. You will get two hash code as below. It has a break on the singleton pattern.

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 325040804

Prevent Singleton pattern from Reflection

There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw run time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.

    private Singleton() {
        if( instance != null ) {
           throw new InstantiationError( "Creating of this object is not allowed." );
        }
    }

Deserialization

In serialization, we can save the object of a byte stream into a file or send over a network. Suppose if you serialize the Singleton class and then again de-serialize that object will create a new instance, hence deserialization will break the Singleton pattern.

Below code is to illustrate how the Singleton pattern breaks with deserialization.

Implements Serializable interface for Singleton Class.

DeserializationSingleton.Java

package demo1;

import java.io.*;

public class DeserializationSingleton {

    public static void main(String[] args) throws Exception {

        Singleton instanceOne = Singleton.getInstance();
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text"));
        out.writeObject(instanceOne);
        out.close();

        ObjectInput in = new ObjectInputStream(new FileInputStream("file.text"));
        Singleton instanceTwo = (Singleton) in.readObject();
        in.close();

        System.out.println("hashCode of instance 1 is - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 is - " + instanceTwo.hashCode());
    }

}
The output is below and you can see two hashcodes.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 381259350

Prevent Singleton Pattern from Deserialization

To overcome this issue, we need to override readResolve() method in Singleton class and return same Singleton instance. Update Singleton.java, with below method.

   protected Object readResolve() { 
           return instance; 
     }  

Now run above DeserializationDemo class and see the output.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 2125039532

Cloning

Using the "clone" method we can create a copy of original object, samething if we applied clone in singleton pattern, it will create two instances one original and another one cloned object. In this case will break Singleton principle as shown in below code.

Implement the "Cloneable" interface and override the clone method in the above Singleton class.

Singleton.java


    @Override
    protected Object clone() throws CloneNotSupportedException  {
        return super.clone();
    }

Then Test with cloning for breaking the singleton
CloningSingleton.java


public class CloningSingleton {
    public static void main(String[] args) throws CloneNotSupportedException, Exception {
        Singleton instanceOne = Singleton.getInstance();
        Singleton instanceTwo = (Singleton) instanceOne.clone();
        System.out.println("hashCode of instance 1 - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 - " + instanceTwo.hashCode());
    }

}

Here is the output

hashCode of instance 1 - 1836019240
hashCode of instance 2 - 325040804

If we see the above output, two instances have different hashcodes means these instances are not the same.


Prevent Singleton Pattern from Cloning

In the above code, breaks the Singleton principle i. e created two instances. To overcome the above issue we need to implement/override clone() method and throw an exception CloneNotSupportedException from clone method. If anyone try to create clone object of Singleton, it will throw an exception as see below code.

    @Override
    protected Object clone() throws CloneNotSupportedException  {
        throw new CloneNotSupportedException();
    }

Now we can run the CloningSingleton class, it will throw CloneNotSupportedException while creating a clone object of Singleton object.


13

View comments

I am
I am
Archives
Total Pageviews
Total Pageviews
2 0 5 6 2 3 0
Categories
Categories
Loading