Google

Jul 5, 2014

Java Executor service to run concurrently and sequentially with strategy design pattern - part 3

1. Define the interface

Part 1: Running concurrent threads
Part 2: Running sequential threads
Part 3: Creating a strategy class using the strategy design pattern to be able switch between running concurrently and sequentially.

package com.writtentest13;

import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

public interface ExecutorStrategy {
 ExecutorService getExecutor(Collection<? extends Callable> tasks);
 ExecutorService getExecutor(Callable<?>... tasks);
}


2. Define the implementation.

package com.writtentest13;

import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * What is the strategy to execute sequentially in current thread or concurrently?
 * 
 * if no of tasks > threshold then concurrent, else sequentially single
 */
public class TaskExecutorStrategy implements ExecutorStrategy {

 public static final int DEFAULT_THRESHOLD = 1;

 private int threshold = DEFAULT_THRESHOLD;

 private ExecutorService currentThreadExecutor;
 private ExecutorService concurrentExecutor;

 public TaskExecutorStrategy() {
    init();
 }

 public TaskExecutorStrategy(int threshold, int poolSize) {
    this.threshold = threshold;
    init();
 }

 
 private void init() {
    this.currentThreadExecutor = new DefaultThreadExecutor();
    this.concurrentExecutor = Executors.newCachedThreadPool();
 }

 @Override
 public ExecutorService getExecutor(Collection<? extends Callable> tasks) {
    return (tasks.size() > this.threshold) ? this.concurrentExecutor : this.currentThreadExecutor;

 }

 @Override
 public ExecutorService getExecutor(Callable<?>... tasks) {
    return (tasks.length > this.threshold) ? this.concurrentExecutor : this.currentThreadExecutor;
 }

}


3. Use the strategy

package com.writtentest13;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

/**
 * Tasks are executed concurrently in a thread pool
 */
public class ThreadExecutorMainStrategy  {

 private ExecutorStrategy executorStrategy;

 public static void main(String[] args) {
    ThreadExecutorMainStrategy main = new ThreadExecutorMainStrategy();

  
  List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();

  // create dummy tasks
  for (int i = 1; i <= 5; i++) {
     tasks.add(main.createTask(i));
  }
  
  
  main.executorStrategy = new TaskExecutorStrategy();
  ExecutorService executor = main.executorStrategy.getExecutor(tasks);
  
 
  // submit the tasks to the concurrentThreadExecutor
  try {
    executor.invokeAll(tasks);

  } catch (InterruptedException e) {
    e.printStackTrace();
  }

  System.out.println("Completed .........");

 }

 private Callable<Boolean> createTask(final int i) {

  Callable<Boolean> task = new Callable<Boolean>() {

   @Override
   public Boolean call() throws Exception {
      System.out.println("Performing task " + i + " on thread - " + Thread.currentThread().getName());
      return true;
   }

  };

  return task;

 }
}


The output will be

Performing task 1 on thread - pool-1-thread-1
Performing task 3 on thread - pool-1-thread-3
Performing task 2 on thread - pool-1-thread-2
Performing task 5 on thread - pool-1-thread-5
Performing task 4 on thread - pool-1-thread-4
Completed .........


Now if you change the execution strategy arguments to

//threshold = 7, no of threads  = 5
main.executorStrategy = new TaskExecutorStrategy(7,5);


The output will be

Starting to execute task ...
Performing task 1 on thread - main
Finished executing task ...
Starting to execute task ...
Performing task 2 on thread - main
Finished executing task ...
Starting to execute task ...
Performing task 3 on thread - main
Finished executing task ...
Starting to execute task ...
Performing task 4 on thread - main
Finished executing task ...
Starting to execute task ...
Performing task 5 on thread - main
Finished executing task ...
Completed .........


You can create different strategies by implementing the interface ExecutorStrategy.

Labels:

Jun 25, 2014

What is the difference between strategy and command design patterns?

Many design patterns look similar, but there are subtle differences as I explained the differences between Proxy, Decorator, Adapter, Bridge, and Facade design patterns Why do Proxy, Decorator, Adapter, Bridge, and Facade design patterns look very similar? What are the differences? In this post, let's compare strategy and command patterns.

Q. What is the difference between a strategy and a command pattern?
A. Firstly, some example

Strategy - quicksort or mergesort, simple vs compound interest calculations, etc
Command - Open or Close actions, redo or undo actions, etc. You need to know the states undo.


Strategy:

public interface AbstractStrategy {
     abstract void execute(Object arg);
}


public class ConcreteStrategy implements AbstractStrategy {

    @Override
    public void execute(Object arg) {
        // Work with passed-in argument.
    }

}


Command:

public interface AbstractCommand {
     abstract void execute();
}


public class ConcreteCommand implements AbstractCommand {

    private Object arg;

    public ConcreteCommand(Object arg) {
        this.arg = arg;
    }

    @Override
    public void execute() {
        // Work with own state.
    }

}



Q. Can you spot the subtle differences?
A.
  1. Strategy handles how something should be done by taking the supplied arguments in the execute(....) method. For example simple and compound interest will be different classes like SimpleInterestStrategy and CompoundInterestStrategy with different algorithms. Command creates an object out of what needs to be done (i.e. hold state) so that these command objects can be passed around between other classes. The actions the command represent can be undone or redone by maintaining the state. There will tend to be a large number of distinct Command objects that pass through your application.
  2. Design patterns provide a common vocabulary among the designers and developers. So, by looking at the classes and interfaces suffixed with Strategy and Command, the designers and users will understand the intent (i.e. point 1)


Command design pattern example:

Here is an example where requests are batched and then either committed as a batch or if an exception is thrown, rolled back as a batch. 2 types of command objects are used to increment and decrement the count of number of requests added to a batch. Both these command objects maintain the count via the CountState object.

Step 1: The interface for the command objects.

public interface AbstractCommand {
    abstract void execute();
    abstract void undo();
}


Step 2: A POJO object to store count data.

public final class CountState {

  private int count;
  
  public void increment(){
   ++this.count;
  }
  
  public void decrement() {
   --this.count;
  }
  
  public int getCount() {
   return this.count;
  }
}


Step 3: Increment and Decrement command objects

public class IncrementCommand implements AbstractCommand {

 private CountState count;
 
 public IncrementCommand(CountState count) {
  this.count = count;
 }

 private String previousString;

 @Override
 public void execute() {
  count.increment();
  
 }

 @Override
 public void undo() {
  count.decrement();
 }
 
}


public class DecrementCommand implements AbstractCommand {

 private CountState count;
 
 public DecrementCommand(CountState count) {
  this.count = count;
 }

 private String previousString;

 @Override
 public void execute() {
  count.decrement();
  
 }

 @Override
 public void undo() {
  count.increment();
 }
 
}




Step 4: Now, the request processor class that is responsible for adding batching requests via addRequest() or removeRequest() methods and batch execution or rollback via commitBatch() and rollbackBatch() methods. This makes makes use of the command objects.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessor {

 private Deque<AbstractCommand> commandStack = null;
 private AbstractCommand incCmd;
 private AbstractCommand decCmd;

 private Map<String, String> requestCollection = new HashMap<>();

 public RequestProcessor(AbstractCommand incCmd, AbstractCommand decCmd) {
  this.commandStack = new ArrayDeque<>();
  this.incCmd = incCmd;
  this.decCmd = decCmd;
 }

 public void addRequest(String requestId, String requestTxt) {
  incCmd.execute();
  commandStack.push(incCmd);
  requestCollection.put(requestId, requestTxt);
 }

 public void removeRequest(String requestId) {
  decCmd.execute();
  commandStack.push(decCmd);
  requestCollection.remove(requestId);
 }

 public void commitBatch() {
  // ...logic to action all the requests
  // left out for brevity
  requestCollection.clear();
  this.commandStack = new ArrayDeque<>();
 }

 public void rollbackBatch() {
  AbstractCommand cmd = null;
  while (!commandStack.isEmpty()) {
   cmd = commandStack.pop();
   cmd.undo();
  }
 }
}


Finally, the client app that makes use of the RequestProcessor and other objects.

public class ClientApp {

 public static void main(String[] args) {
  CountState state = new CountState();
  AbstractCommand incCmd = new IncrementCommand(state);
  AbstractCommand decCmd = new DecrementCommand(state);
  RequestProcessor processor = new RequestProcessor(incCmd, decCmd);

  processor.addRequest("1", "productcode:123, price:25.50");
  processor.addRequest("2", "productcode:456, price:12.50");
  processor.addRequest("3", "productcode:789, price:14.50");

  // ...

  processor.removeRequest("3");

  try {

   processor.commitBatch();
   System.out.println("number of requests processed:" + state.getCount()); // 2
   throw new RuntimeException();

  } catch (Exception ex) {
   processor.rollbackBatch();
   System.out.println("number of requests processed:" + state.getCount()); // 0
  }
 }
}


The strategy deign pattern example is covered in Java design pattern interview questions and answers: strategy and factory pattern

Labels: ,

Jun 6, 2014

Why do Proxy, Decorator, Adapter, Bridge, and Facade design patterns look very similar? What are the differences?

There are often patterns that look very similar, but differ in their intent. Most patterns use polymorphism with interface inheritance. Strategy and state design patterns are very similar as well. Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. Facade design pattern is a container for the classes in another sub system.

One of the reasons to use a design pattern is to talk the common vocabulary with the designers and the developers. The intent and naming conventions (e.g. FileLoaderProxy, FileLoaderBridege, etc) of these design patterns form a common vocabulary.

Asking a few questions helps.
  • How about a facade to simplify the subsystems by minimizing the number of fine grained invocations from the client?
  • How about a proxy to provide access control?
  • How about adding a decorator to enhance current behavior? How about a decorator to fix explosive inheritance through composition at run time? 
  • Do we need an adapter to talk to third-party API
  • Do we have different permutations? what would our hierarchy look like? How about a bridge design pattern to re-factor this exponentially explosive inheritance 
  • Do we want to bind this association at compile time or run time?

Proxy 

is good to act as a surrogate to provide performance optimization, synchronization, remote access, house keeping, etc. The binding of the actual subject to the proxy happens at compile-time.



Decorator

is  good to avoid out of control type hierarchies. A decorator is also known as a "smart proxy" because it enhances the behavior of a subject at run time. In other words binding is dynamic. The Java I/O classes are good example of a decorator design pattern. At run time different permutations can can be carried out via composition.



Adapter

Adapts at run time like the decorator design pattern. Adapter design pattern is one of the structural design patterns and its intent is to get two unrelated interfaces work together. Think of using a laptop in UK that was bought in Japan as the sockets are different, and you need an adapter. So, the adapter's intent is to adapt between the Japanese  laptop plug with UKs wall socket. The key point is that parties are different. Japanese laptop used in third-party or external (i.e. UK) wall socket.



Adapter is used when you have an abstract interface, for example a JDBC API and you want to map that interface to another object which has similar functional role, but a different interface, for example different JDBC drivers for different databases like Oracle, Sybase, DB2, SQL server, MySQL, etc. The JEE have multiple adaptors for JMS, JNDI, JDBC, JCA, etc. The drivers and implementations are generally provided by the third party vendors. For example, JMS implementations provided by third-party vendors and open source providers web Methods, IBM MQ Series, ActiveMQ, etc.

 You can accomplish this using either inheritance or composition.
  •  Class Adapter – This form uses Java inheritance and extends the source interface.
  •  Object Adapter – This form uses Java Composition and adapter contains the source object.

Bridge

is very similar to Adapter, but you call it a Bridge when you define both the abstract interface and the underlying implementation (no external or third-party vendors). Adapter makes things work after they're designed, but bridge makes them work before they are. Abstraction and implementation should be bound at compile time. You need to swap for different implementations. For example, you are designing a graphics application that needs to swap between graphics driver and printer driver for the same draw( ) .

As shown below, you can have different permutations of  a user like local user, external user, provisional user, local admin user, local support user, and so on. re-factoring this into users and roles will prevent the explosion of class hierarchy. A decorator does this at run-time, whereas a bridge does this at compile-time.



If you are wring unit tests, the bridge pattern is indispensable when it comes down to implementing mocks and mock services. You can use a bridge (or mock) web services in integration testing until the real services become available.


Facade 

is a higher-level interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to a wrapper.



For example, when you have remote calls via EJBs, Web Services, RMI, etc, making fine grained remote calls each time can be expensive and adversely affects performance. So, in between the caller and the callee, you can define a facade that makes many fine grained local calls for a single remote call from the caller.It also simplifies the client code with just a single method call by hiding the complexity of the subsystem classes via a facade.




Q. How does a strategy design pattern differ from a state design pattern?

The Strategy pattern is really about having a different implementation that accomplishes the same thing, so that one implementation can replace the other while the caller does not change. The Strategy pattern deals with how an object performs a certain task? -- it encapsulates an algorithm or processing logic. The logic and algorithms can be improved and swapped without the caller not knowing anything about it.

For example, as a driver of a car, the steering wheel is your interface to interact, but over the years the implementations of steering mechanisms have improved like manual steering to power steering, and so on without affecting how you drive a car.


The State pattern is about doing different things based on the state, while leaving the caller relieved from the burden of accommodating every possible state. The State pattern deals with what state an object is in? or what type an object is? -- it encapsulates state-dependent behavior


For example, thread goes into different states like blocked, ready, running, etc. Placing a trade order on a stock market will have states like pending, filled, partially-filled, rejected, executed, etc.

This was intended to be very simple explanation with diagrams and examples. For more on design patterns with working code and example, search this blog or click on the "design pattern" tag cloud at the bottom.

Labels:

Jun 5, 2014

Difference between proxy and decorator design patterns with a Java example

Are you a Java beginner or a seasoned professional? Java design pattern interview questions are unavoidable. You should do just more than giving factory or singleton design pattern as examples. Good interviewers will be looking for key terms like intent, and practical examples.

In the last post, I looked at the difference between a decorator design pattern and a chain of responsibility design pattern. In this post, let's look at the difference between a decorator and a proxy design design. Often, the proxy, decorator, and the adapter design patterns look similar, but the intent and how you use them are different.

Q. Explain Proxy is compile-time, and decorator and adapter patterns are at run time?
A. A proxy simply delegates all calls to the underlying subject for purposes such as delaying costly operations, hiding the remote object, or providing access control, etc. This basically means that what a proxy can do is decided at compile time and cannot be changed by the calling code after substantiation. Using the decorator pattern the behavior of the underlying object can be changed at run time by adding multiple decorators to it. This addition of behavior takes place at run time.




Q. What is the difference between a decorator and a proxy?
A.

Intent: Decorator is for enhancement (as the name guide), Proxy is for helping with improving performance via lazy loading, controlling access, and hiding remoteness.

Occurrence: Decorator is  run time, and Proxy is compile time, Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way and store the subject in the proxy, whereas Decorator or Adapter are assigned to the subject at run time, knowing only subject's interface.



Step 1: Define the interface

import java.io.File;

public interface FileLoader {
       void loadData(File file);
}

Step 2: Define the subject. which does the actual work of loading the file data.

import java.io.File;

public class FileLoaderImpl implements FileLoader {
 
 @Override
 public void loadData(File file) {
  System.out.println("loading data ...........");
 }
}

Step 3: The proxy that provides access control, lazy loading, and synchronization, and then delegates the invocation to the subject. Proxy knows who the subject is, and cannot be changed once constructed.

import java.io.File;

public class FileLoaderProxy implements FileLoader {

 private User user;
 private volatile FileLoader fileLoader; ////visible to other threads
 private static Object lock = new Object();

 public FileLoaderProxy(User user) {
  this.user = user;
 }

 @Override
 public void loadData(File file) {
  // proxy providing access control
  if (user.okToAccess()) {
   // proxy providing synchronisation
   synchronized (lock) {
    // proxy laziliy load
    if (fileLoader == null) {
     fileLoader = new FileLoaderImpl();
    }
    fileLoader.loadData(file);
   }
  } else {
   throw new RuntimeException("Access denied for user: " + user.getName());
  }
 }
}



Step 4: The caller, client or invoker that communicates to the subject via the proxy.
import java.io.File;

public class FileLoaderTest {
 
 public static void main(String[] args) {
  User user = new User("test", "test");
  FileLoader proxyLoader = new FileLoaderProxy(user);
  proxyLoader.loadData(new File("c:\temp\temp.txt"));  
 }
}


Q. Can you give some practical examples of proxy design pattern?
A.

1. Hibernate uses proxy objects to provide lazy loading.
2. RMI and EJB uses proxy stubs, which know how to communicate remotely with the skeleton.
3. Any other scenarios where proxy

-- hides information about the real object (i.e. subject)
-- provides optimization like lazy loading or synchronization to provide thread-safety
-- provides house keeping tasks like auditing/logging or services like deadlock retry with dynamic proxies.


You may also like:

Labels:

Jun 4, 2014

Understanding Decorator and chain of responsibility design patterns with Java examples

Some design patterns do have subtle differences, and it is important to understand the intent of a pattern. Decorator and chain of responsibility may look similar but the intent is different. Decorator has a subtle difference with a proxy design pattern.

Q. What is a decorator design pattern?
A. A decorator enhances the behavior of an object at run time. Decorators provide a flexible alternative to sub classing for extending functionality. Java I/O API is a good example of a decorator design pattern.  If you were to implement this with an inheritance hierarchy (happens at compile time) you would have ended up with a fragile and large hierarchy. Instead, it was designed with decorator design pattern. You can have different combinations at run time.

//decorating at run time
String inputText = "Some text to read";
ByteArrayInputStream bais = new ByteArrayInputStream(inputText.getBytes());
Reader isr = new InputStreamReader(bais);
BufferedReader br = new BufferedReader(isr);
br.readLine(); 



So, why favor composition over inheritance?


Q. What is a chain of responsibility design pattern?
A. Use the Chain of Responsibility pattern when you can conceptualize your program as a chain made up of links, where each link (or processor) can either handle a request/command or pass it down the chain.

Q. How does chain of responsibility differ from a decorator design pattern?
A. The fact that you can break the chain at any point and each chain can either handle or pass it differentiates the Chain of Responsibility pattern from the Decorator pattern. In other words,  if you chain, each link will be called along the chain, and with a decorator, you're not guaranteed of this order, but you can be confident that additional responsibilities can be attached.



Chain link interface that passes the request or command object java.lang.Number

//Chain link interface
public interface NumberHandlerChain {
 void setNextChain(NumberHandlerChain nextChain);
 void handleNumber(Number number);
}

First chain that adds 1 if the command or request is an odd number

public class OddNumberHandler implements NumberHandlerChain {
 private NumberHandlerChain nextChain;

 @Override
 public void setNextChain(NumberHandlerChain nextChain) {
  this.nextChain = nextChain;
 }

 @Override
 public void handleNumber(Number number) {
  if (number.longValue() % 2 != 0) {
   number = number.longValue() + 1;
   System.out.println(this.getClass().getName() + " : " + number);
  }

  if (this.nextChain != null) {
   this.nextChain.handleNumber(number);
  }
 }
}

Second chain that adds 2 if the command or request is an even number

public class EvenNumberHandler implements NumberHandlerChain {
 private NumberHandlerChain nextChain;

 @Override
 public void setNextChain(NumberHandlerChain nextChain) {
  this.nextChain = nextChain;
 }

 @Override
 public void handleNumber(Number number) {
  if (number.longValue() % 2 == 0) {
   number = number.longValue() + 2;
   System.out.println(this.getClass().getName() + " : " + number);
  }

  if(this.nextChain != null) {
     this.nextChain.handleNumber(number);
  }
 }
}

Third chain that adds 5 if the command or request is a multiple of 5

public class MultipleOfFiveHandler implements NumberHandlerChain {
 private NumberHandlerChain nextChain;

 @Override
 public void setNextChain(NumberHandlerChain nextChain) {
  this.nextChain = nextChain;
 }

 @Override
 public void handleNumber(Number number) {
  if (number.longValue() % 5 == 0) {
   number = number.longValue() + 5;
   System.out.println(this.getClass().getName() + " : " + number);
  }

  if (this.nextChain != null) {
   this.nextChain.handleNumber(number);
  }

 }
}

Sender who constructs the Request/Command objects which are java.lang.Number objects and pass them down the chain of processors (i.e implementation of NumberHandlerChain).

//Sender
public class CorTest {
 private NumberHandlerChain chain;

 public static void main(String[] args) {
  CorTest sender = new CorTest();

  NumberHandlerChain chain1 = new OddNumberHandler();
  NumberHandlerChain chain2 = new EvenNumberHandler();
  NumberHandlerChain chain3 = new MultipleOfFiveHandler();

  sender.setChain(chain1);
  chain2.setNextChain(chain3);
  chain1.setNextChain(chain2);

  sender.getChain().handleNumber(7); //all 3 chains handles
  sender.getChain().handleNumber(4); //only EvenNumberHandler handles this
 }

 public NumberHandlerChain getChain() {
  return chain;
 }

 public void setChain(NumberHandlerChain chain) {
  this.chain = chain;
 }
}


Output:

com.cor.OddNumberHandler : 8
com.cor.EvenNumberHandler : 10
com.cor.MultipleOfFiveHandler : 15
com.cor.EvenNumberHandler : 6


7 becomes 8 by adding 1, then 10 by adding 2, and then 15 by adding 5.
4 becomes 6 by adding 2.

So, order does matter.


Q. Can you think of  practical examples of chain of responsibility design pattern?

Example 1: Java’s own Exception Handling mechanism because

1. Sender of an exception will not know which object in the chain will serve its request.
2. Each processor in the chain may decide to serve the exception by catching and logging  or
3. wrapping it with an application specific exception and then rethrowing it to the caller or
4. don't handle it and leave it to the caller


Example 2: Servlet filters are implementation of the chain of responsibility pattern.

void doFilter(..) { 
    // do things like security check, parsing payload, etc before the servlet gets called

    // invoke the servlet, or any other filters mapped to the target servlet
    chain.doFilter(..);

    // do stuff after the servlet finishes
}



Example 3: An interceptor is generally a link in a chain of responsibility. Interceptors in Java frameworks like Spring MVC, Struts 2, etc intercept, handle or pass a message down the chain for other interceptors to handle.


More design patterns with Java examples. Will cover difference between decorator and proxy design pattern later.

Labels:

Jun 2, 2014

Event Driven Programming Java example tutorial style - part 2 JMX enabling & jconsole

This extends the basic tutorial on event driven programming in Java. This tutorial covers JMX enabling the EventHub class vian MBeans and monitoring through JMX compliant tool like jconsole.

Step 1: Define the interface with the methods that are intractable via the JMX compliant client like jconsole.


package com.writtentest14;

public interface EventHubMBean {

 /**
  * Attributes
  */
    long getEventCount();
   
    
    /**
     *   Operations
     */
    void fireEventById(String eventId);
}


Step 2: Define the implementation of the above interface. Note it extends StandardMBean from the Java management API.

package com.writtentest14;

import javax.management.StandardMBean;

public class StandardEventHubMBean extends StandardMBean implements EventHubMBean {

    private EventHub eventHub;
    
    public StandardEventHubMBean(EventHub eventHub) {
        super(EventHubMBean.class, false);
        this.eventHub = eventHub;
    }

    @Override
    public long getEventCount() {
        return this.eventHub.getEventCount();
    }

    @Override
    public void fireEventById(String eventId) {
        Event event = new Event(eventId);
        this.eventHub.fire(event);
    }

}


Step 3: Now, the revised EventHib with JMX enabled.

package com.writtentest14;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

/**
 * register and unregister event listeners
 */

public class EventHub {

 private static final EventHub INSTANCE = createInstance();
 
 private ConcurrentMap<String, List<EventListener<Event>>> registeredListeners = new ConcurrentHashMap<String, List<EventListener<Event>>>();

 private EventDispatcher synchronousDispatcher;

 private AtomicLong eventCount = new AtomicLong();

 public EventHub() {
  registerMBean();
 }

 public static EventHub instance() {
  return INSTANCE;
 }

 public EventHub(EventDispatcher synchronousDispatcher) {
  this.synchronousDispatcher = synchronousDispatcher;
  registerMBean();
 }

 public long getEventCount() {
  return this.eventCount.get();
 }

 

 private long getNextEventNumber() {
  return this.eventCount.incrementAndGet();
 }

 protected EventDispatcher getSynchronousDispatcher() {
  return this.synchronousDispatcher;
 }

 public void setSynchronousDispatcher(EventDispatcher dispatcher) {
  this.synchronousDispatcher = dispatcher;
 }

 public void fire(Event event) {
  dispatch(event, getSynchronousDispatcher());
 }

 
 public synchronized void addListener(String eventId, EventListener<Event> listener) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(eventId);
  if (listeners != null) {
   listeners.add(listener);
  } else {
   listeners = new CopyOnWriteArrayList<EventListener<Event>>();
   listeners.add(listener);
   this.registeredListeners.put(eventId, listeners);
  }

 }


 public void removeListener(String eventId, EventListener<Event> listener) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(eventId);
  if (listeners != null) {
   listeners.remove(listener);

  }
 }

 private void registerMBean() {
  MBeanServer server = getMBeanServer();
  StandardEventHubMBean mbean = new StandardEventHubMBean(this);
  try {
   server.registerMBean(mbean, getMBeanObjectName());
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 protected void dispatch(Event event, EventDispatcher dispatcher) {
  getNextEventNumber();
  List<EventListener<Event>> listeners = getListeners(event);
  if (!listeners.isEmpty()) {

   dispatcher.dispatch(event, listeners);

  }
 }
 
  private static EventHub createInstance() {
         EventHub instance = new EventHub(new SimpleSynchronousDispatcher());
         return instance;
     }

 private List<EventListener<Event>> getListeners(Event event) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(event.getId());
  return (listeners != null) ? listeners : Collections.<EventListener<Event>>emptyList();
 }

 private MBeanServer getMBeanServer() {
  ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
  if (servers != null && !servers.isEmpty()) {
   return (MBeanServer) servers.get(0);
  } else {
   // If it all fails, get the platform default...
   return ManagementFactory.getPlatformMBeanServer();
  }
 }

 private ObjectName getMBeanObjectName() {
  try {
   String name = "com.com.writtentest14:type=EventHub,instance=" + hashCode();
   return new ObjectName(name);
  } catch (MalformedObjectNameException e) {
   throw new RuntimeException(e);
  }
 }

}


Step 4: Run the EveneHubMain defined in part 1. Type jconsole from a DOS command prompt.



Step 5: You can now view the attributes and operations defined in EventHubMBean interface.  It displays the number of events processed.



Step 6:  You can also fire an event by entering an event name and clicking on fireEventById(  ).




Labels: , ,

May 30, 2014

How to create a well designed Java application? SOLID and GoF design patterns strive for tight encapsulation, loose (or low) coupling and high cohesion

A software application is built by coupling various classes, modules, and components. Without coupling, you can't build a software system. But, the software applications are always subject to changes and enhancements. So, you need to build your applications such a way that they can easily adapt to growing requirements and easy to maintain and understand. 3 key aspects to achieve this are

1. Tight encapsulation.
2. Loose (or low) coupling.
3. High cohesion.

The purpose of SOLID design principles and GoF design patterns is to achieve the above goal.


What is encapsulation?

Encapsulation is about hiding the implementation details. This means

1) Hiding data by setting member variables with private access level and providing public methods with pre and post condition checks to access the member variables.




2) Coding to interface and not implementation: Using a given class or module by its interface, and not needing to know any implementation details.

Badly Encapsulated: Directly dependent on ProductServiceImpl




Tightly Encapsulated: Dependent on the interface ProductService. The implementation can change from ProductServiceImpl to InternationalizedProductServiceImpl  without  the callers or clients OrderServiceImpl, SalesEnquiryServiceImpl, and CustomerServiceImpl  needing to know about the implementation details.





SOLID Principle:  LSP (Liskov substitution principle), DIP (Dependency inversion principle), and SRP (Single Responsibility Principle) strives to create tight encapsulation.


Q. Does tight encapsulation promote loose coupling?
A. Yes, poor encapsulation can allow tight coupling  as it will be possible to access non-encapsulated variables directly from another class, making it dependent on the implementation of the class that contains those variables. It is also possible to have poor encapsulation with loose coupling. So, encapsulation and coupling are different concepts, but poor encapsulation makes it possible to create tight coupling. 



What is coupling?

Coupling in software development is defined as the degree to which a module, class, or other construct, is tied directly to others. You can reduce coupling by defining intermediate components (e.g. a factory class or an IoC container like Spring) and interfaces between two pieces of a system. Favoring composition over inheritance can also reduce coupling.

Let's write some code for the above UML diagram to demonstrated loose coupling with GoF factory design pattern.

Step 1: Define the interfaces for the above diagram

public interface OrderService {
      abstract void process(Product p);
}


import java.math.BigDecimal;

public interface ProductService {
    abstract BigDecimal getDiscount(Product p);
}


Step 2: Define the implementation class for ProductService

public class ProductServiceImpl implements ProductService {

 @Override
 public BigDecimal getDiscount(Product p) {
  //logic goes here
  return null;
 }

}


Step 3: Factory eliminate need to bind application specific classes into the code. The code only deals with the ProductService interface , and can therefore work with any user-defined concrete implementations like ProductServiceImpl or InternationalizedProductServiceImpl.

public final class ProductServiceFactory {
   
 private ProductServiceFactory(){}
 
 public static ProductService getProductService() {
  ProductService ps = new ProductServiceImpl(); // change impl here
  return ps;
 }
}


Step 4: The caller or client class who is loosely coupled to ProductService via the ProductServiceFactory.

import java.math.BigDecimal;

public class OrderServiceImpl implements OrderService {
 
 ProductService ps;
 
 @Override
 public void process(Product p) {
  ps = ProductServiceFactory.getProductService();
  BigDecimal discount = ps.getDiscount(p);
  //logic
 }

}

So, if you want to change over from ProductServiceImpl  to  InternationalizedProductServiceImpl, all you have to do is make a change in the ProductServiceFactory class. An alternative approach to using a factory is to use an IoC container like Spring instead of a factory class to loosely wire the dependencies via dependency injection at run time.


Q. How do you create loose coupling?
A. By abstracting many of the implementation needs into various interfaces and introducing the concepts of OCP and DIP, you can create a system that has very low coupling.



What is cohesion? Cohesion is the extent to which two or more parts of a system are related and how they work together to create something more valuable than the individual parts. You don't want a single class to perform all the functions (or concerns) like being a domain object, data access object, validator, and a service class with business logic. To create a more cohesive system from the higher and lower level perspectives, you need to break out the various needs into separate classes.

Coupling happens in between classes or modules, whereas cohesion happens within a class.



Q. How do you create high cohesion?
A. You can get higher cohesion with a combination of low coupling and SRP (Single Responsibility Principle from SOLID), which allows you to  stack a lot of small pieces (e,g. Service, DAO, Validator, etc) together like puzzles to create something larger and more complex.



So, think, tight encapsulation, loose (low) coupling, and high cohesion.


Labels: ,

May 29, 2014

Event Driven Programming: Java example tutorial style - part 1

Event Driven Architecture aka EDA loosely couples event producers and event consumers.

An event can be defined as "a change in state". For example, when an event producer fires an event to notify all its registered listeners that either "securities" or "security prices" have been loaded, the listeners are notified to update their data via a synchronous or asynchronous dispatcher. Both the "Event" producers and listeners are loosely coupled via an "EventHub" and "Event". An "EventHub" is used to register and unregister listeners.

The "EventHub" can be registed as a JMX bean to control behaviors at runtime via a jconsole like firing an event, count number of events, etc.

A number of tutorials will take you through writing event driven code in Java along with registering as MBean to interact via a JMX compliant tool like jconsole.



Let's define the interfaces and implementation classes.


Step 1: Define the "Event" class from which all other events can be derived from.

package com.writtentest14;

import java.util.Date;

public class Event {

 private String id;
 private Date timeStamp;
 
 public Event(String id) {
  super();
  this.id = id;
  this.timeStamp = new Date();
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public Date getTimeStamp() {
  return timeStamp;
 }

 public void setTimeStamp(Date timeStamp) {
  this.timeStamp = timeStamp;
 }

}


Step 2: Define the interface for the listeners

package com.writtentest14;

public interface EventListener<T extends Event> {
 void onEvent(T event);
}


Step 3:  Define the dispatcher interface.

package com.writtentest14;

import java.util.List;


public interface EventDispatcher {

    void dispatch(Event event, List<EventListener<Event>> listeners);    
}


Step 4: The dispatcher implementation. It could be synchronous or asynchronous dispatcher. Let's keep it simple by defining a synchronous dispatcher.

package com.writtentest14;

import java.util.List;

public class SimpleSynchronousDispatcher implements EventDispatcher {

    @Override
    public void dispatch(Event event, List<EventListener<Event>> listeners) {
        for (EventListener<Event> listener : listeners) {
            listener.onEvent(event);
        }
    }
}

Step 5:  Define the EventHub. Binds and unbinds listeners and invokes the dispatcher to dispatch the events.

package com.writtentest14;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

/**
 * register and unregister event listeners
 */

public class EventHub {

 private static final EventHub INSTANCE = createInstance();
 
 private ConcurrentMap<String, List<EventListener<Event>>> registeredListeners = 
                                   new ConcurrentHashMap<String, List<EventListener<Event>>>();

 private EventDispatcher synchronousDispatcher;

 private AtomicLong eventCount = new AtomicLong();

 public EventHub() {
 }

 public static EventHub instance() {
  return INSTANCE;
 }

 public EventHub(EventDispatcher synchronousDispatcher) {
  this.synchronousDispatcher = synchronousDispatcher;
 }

 public long getEventCount() {
  return this.eventCount.get();
 }

 private long getNextEventNumber() {
  return this.eventCount.incrementAndGet();
 }

 protected EventDispatcher getSynchronousDispatcher() {
  return this.synchronousDispatcher;
 }

 public void setSynchronousDispatcher(EventDispatcher dispatcher) {
  this.synchronousDispatcher = dispatcher;
 }

 public void fire(Event event) {
  dispatch(event, getSynchronousDispatcher());
 }

 public synchronized void addListener(String eventId, EventListener<Event> listener) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(eventId);
  if (listeners != null) {
   listeners.add(listener);
  } else {
   listeners = new CopyOnWriteArrayList<EventListener<Event>>();
   listeners.add(listener);
   this.registeredListeners.put(eventId, listeners);
  }

 }

 public void removeListener(String eventId, EventListener<Event> listener) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(eventId);
  if (listeners != null) {
   listeners.remove(listener);

  }
 }

 protected void dispatch(Event event, EventDispatcher dispatcher) {
  getNextEventNumber();
  List<EventListener<Event>> listeners = getListeners(event);
  if (!listeners.isEmpty()) {

   dispatcher.dispatch(event, listeners);

  }
 }
 
  private static EventHub createInstance() {
         EventHub instance = new EventHub(new SimpleSynchronousDispatcher());
         return instance;
     }

 private List<EventListener<Event>> getListeners(Event event) {
  List<EventListener<Event>> listeners = this.registeredListeners.get(event.getId());
  return (listeners != null) ? listeners : Collections.<EventListener<Event>>emptyList();
 }

}


Step 6: Finally, the EventHubMain that has the main method to run, and creates 3 listeners as  anonymous inner classes, and also acts as a producer to fire events. The listeners and the producer are decoupled via EventHub as the producer and listeners don't interact with each other, but via the EventHub and Event classes.

package com.writtentest14;

import java.util.concurrent.TimeUnit;

public class EventHubMain {

 private static final String PRICE_LOAD_EVENT = "PL_EVENT";
 private static final String SECURITY_LOAD_EVENT = "SL_EVENT";

 public static void main(String[] args) {

  // Anonymous listener1
  EventHub.instance().addListener(PRICE_LOAD_EVENT, new EventListener<Event>() {

   @Override
   public void onEvent(Event event) {
    System.out.println(PRICE_LOAD_EVENT + " received by listener " + this.getClass());
    try {
     TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

  });

  // Anonymous listener2
  EventHub.instance().addListener(SECURITY_LOAD_EVENT, new EventListener<Event>() {

   @Override
   public void onEvent(Event event) {
    System.out.println(SECURITY_LOAD_EVENT + " received by listener " + this.getClass());
    try {
     TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

  });

  // Anonymous listener3
  EventHub.instance().addListener(PRICE_LOAD_EVENT, new EventListener<Event>() {

   @Override
   public void onEvent(Event event) {
    System.out.println(PRICE_LOAD_EVENT + " received by listener " + this.getClass());
    try {
     TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

  });

  // Event dispatcher
  while (true) {
   System.out.println("Event fired " + PRICE_LOAD_EVENT + ".............");
   EventHub.instance().fire(new Event(PRICE_LOAD_EVENT));

   try {
    TimeUnit.SECONDS.sleep(5);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }

   System.out.println("Event fired " + SECURITY_LOAD_EVENT + ".............");
   EventHub.instance().fire(new Event(SECURITY_LOAD_EVENT));

  }
 }

}


Finally, the output if you run the above class, which runs for ever in a while loop.

Event fired PL_EVENT.............
PL_EVENT received by listener class com.writtentest14.EventHubMain$1
PL_EVENT received by listener class com.writtentest14.EventHubMain$3
Event fired SL_EVENT.............
SL_EVENT received by listener class com.writtentest14.EventHubMain$2
Event fired PL_EVENT.............
PL_EVENT received by listener class com.writtentest14.EventHubMain$1


In the next post, I will integrate MBean components with MBean server to manage the EventHub via a JMX client like jconsole.

Labels: ,

May 27, 2014

Understanding Open/Closed Principle (OCP) from the SOLID OO principles with a simple Java example

Spring Interview Questions and Answers Q1 - Q14 are FAQs

Q1 - Q4 Overview & DIP Q5 - Q8 DI & IoC Q9 - Q10 Bean Scopes Q11 Packages Q12 Principle OCP Q14 AOP and interceptors
Q15 - Q16 Hibernate & Transaction Manager Q17 - Q20 Hibernate & JNDI Q21 - Q22 read properties Q23 - Q24 JMS & JNDI Q25 JDBC Q26 Spring MVC Q27 - Spring MVC Resolvers

Q. Is there anything wrong with the following class design? If yes, can the design be improved?

package com.ocp;

import javax.management.RuntimeErrorException;

import org.apache.commons.lang.StringUtils;

public class MathOperation {
 
 public int operate(int input1, int input2, String operator){
  
  if(StringUtils.isEmpty(operator)){
   throw new IllegalArgumentException("Invalid operator: " + operator);
  }
  
  if(operator.equalsIgnoreCase("+")){
   return input1 + input2;
  }
  else if(operator.equalsIgnoreCase("*")){
   return input1 * input2; 
  } else {
   throw new RuntimeException("unsupported operator: " + operator);
  }
 }

}

JUnit test class.

package com.ocp;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class MathOperationTest {
 
 MathOperation operation;
 
 @Before
 public void init(){
  operation = new MathOperation();
 }
 
 @Test
 public void testAddition() {
  Assert.assertEquals(8, operation.operate(5, 3, "+"));
 }
 
 @Test
 public void testMultiplication() {
  Assert.assertEquals(15, operation.operate(5, 3, "*"));
 }

}

A. It’s not a good idea to try to anticipate changes in requirements ahead of time, but you should focus on writing code that is well written enough so that it’s easy to change. This means, you should strive to write code that doesn't have to be changed every time the requirements change. This is what the Open/Closed principle is. According to GoF design pattern authors "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". Spring framework promotes this principle.

In the above example, you can anticipate more operators like "-" (subtraction) and division (/) to be supported in the future and the class "MathOperation" is not closed for modification. When you need to support operators "-" and "%" you need to add 2 more "else if" statements. Whenever you see large if/else or switch statements, you need to think if "Open/Closed" design principle is more suited.


Let's open for extension and close for modifications

In the rewritten example below, the classes AddOperation and MultiplyOperation are closed for modificationbut open for extension by allowing you to add new classes like SubtractOperation and DivisionOperation by implementing the Operation interface.


Define the interface Operation.

package com.ocp;

public interface Operation {
       abstract int operate(int input1, int input2);
}


Define the implementations

package com.ocp;


public class AddOperation implements Operation {

 @Override
 public int operate(int input1, int input2) {
  return input1 + input2;
 }
 
}

package com.ocp;

public class MultiplyOperation implements Operation {

 @Override
 public int operate(int input1, int input2) {
  return input1 * input2;
 }
 
}


Finally, the JUnit test class

package com.ocp;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class MathOperation2Test {
 
 Operation operation;
  
 @Test
 public void testAddition() {
  operation = new AddOperation();
  Assert.assertEquals(8, operation.operate(5, 3));
 }
 
 @Test
 public void testMultiplication() {
  operation = new MultiplyOperation();
  Assert.assertEquals(15, operation.operate(5, 3));
 }

}


This is only a trivial example, but in real life applications, wherever you have large if/else statements, you need to think if OCP can be applied. Spring framework promotes this principle.


Q. Can you explain if the following classes are badly designed? 

Labels: ,

May 23, 2014

Why favor composition over inheritance in Java OOP?

This is a very popular job interview question, and the correct answer depends on the problem you are trying to solve. You need to ask the right questions before deciding one over the other.

Q. How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition?
A. The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.


Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.

Q. Which one to favor, composition or inheritance?
A. The guide is that inheritance should be only used when subclass ‘is a’ super class. Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse.

Reason #1: Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the super class is modified. Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse.

Reason #2: Composition is more flexible as it happens at run time whereas inheritance happens at compile-time.

Reason #3: Composition offers better testability than Inheritance. Composition is easier to test because inheritance tends to create very coupled classes that are more fragile (i.e. fragile parent class) and harder to test in isolation. The IoC containers like Spring, make testing even easier through injecting the composed objects via constructor or setter injection.


Q. Can you give an example of the Java API that favors composition?
A. The Java IO classes that use composition to construct different combinations using the decorator design pattern at run time.

//construct a reader
StringReader sr = new StringReader(“Some Text....”);
//decorate the reader for performance
BufferedReader br = new BufferedReader(sr);
//decorate again to obtain line numbers
LineNumberReader lnr = new LineNumberReader(br);

The GoF design patterns like strategy, decorator, and proxy favor composition for code reuse over inheritance.

Q. Can you a give an example where GoF design patterns use inheritance?
A. A typical example for using inheritance is in frameworks where the template method design pattern is used.

Another common pattern that would use inheritance is Composite pattern.


Q. What questions do you ask yourself to choose composition (i.e. has-a relationship) for code reuse over implementation inheritance (i.e. is-a relationship)? 

A. Do my subclasses only change the implementation and not the meaning or internal intent of the base class? Is every object of type House really “is-an” object of type Building? Have I checked this for “Liskov Substitution Principle

According to Liskov substitution principle (LSP), a Square is not a Rectangle provided they are mutable. Mathematically a square is a rectangle, but behaviorally a rectangle needs to have both length and width, whereas a square only needs a width.

Another typical example would be, an Account class having a method called calculateInterest(..). You can derive two subclasses named SavingsAccount and ChequeAccount that reuse the super class method. But you cannot have another class called a MortgageAccount to subclass the above Account class. This will break the  Liskov substitution principle because the intent is different. The savings and cheque accounts calculate the interest due to the customer, but the mortgage or home loan accounts calculate the interest due to the bank

Violation of LSP results in all kinds of mess like failing unit tests, unexpected or strange behavior, and violation of open closed principle (OCP) as you end up having if-else or switch statements to resolve the correct subclass. For example,

if(shape instanceof Square){
     //....
} 
else if (shape instanceof Rectangle){
    //...
}

If you cannot truthfully answer yes to the above questions, then favor using “has-a” relationship (i.e. composition). Don't use “is-a” relationship for just convenience. If you try to force an “is-a” relationship, your code may become inflexible, post-conditions and invariants may become weaker or violated, your code may behave unexpectedly, and the API may become very confusing. LSP is the reason it is hard to create deep class hierarchies.

Always ask yourself, can this be modeled with a “has-a” relationship to make it more flexible?

For example, If you want to model a circus dog, will it be better to model it with “is a” relationship as in a CircusDog “is a” Dog or model it as a role that a dog plays? If you implement it with implementation inheritance, you will end up with sub classes like CircusDog, DomesticDog, GuideDog, SnifferDog, and StrayDog. In future, if the dogs are differentiated by locality like local, national, international, etc, you may have another level of hierarchy like LocalCircusDog, NationalCicusDog, InternationalCircusDog, etc extending the class CircusDog. So you may end up having 1 animal x 1 dog x 5 roles x 3 localities = 15 dog related classes. If you were to have similar differentiation for cats, you will end up having similar cat hierarchy like WildCat, DomesticCat, LocalWildCat, NationalWildCat, etc. This will make your classes strongly coupled.


If you implement it with interface inheritance, and composition for code reuse, you can think of circus dog as a role that a dog plays. These roles provide an abstraction to be used with any other animals like cat, horse, donkey, etc, and not just dogs. The role becomes a “has a” relationship. There will be an attribute of interface type Role defined in the Dog class as a composition that can take on different subtypes (using interface inheritance) such as CircusRole, DomesticRole, GuideRole, SnifferRole, and StrayRole at runtime. The locality can also be modeled similar to the role as a composition. This will enable different combinations of roles and localities to be constructed at runtime with 1 dog + 5 roles + 3 localities = 9 classes and 3 interfaces (i.e. Animal, Role and Locality). As the number of roles, localities, and types of animals increases, the gap widens between the two approaches. You will get a better abstraction with looser coupling with this approach as composition is dynamic and takes place at run time compared to implementation inheritance, which is static.


Extracted from Core Java Career Essentials, which has more examples, code, and design topics.

Labels: ,

Apr 16, 2014

How to create immutable objects more elegantly in Java?

It is a best practice to create immutable objects where possible because they are inherently thread-safe as you cannot modify them once created, and makes your code easier to debug.

Here is an approach to create immutable objects in Java with the builder design pattern.

The Driver POJO with the Builder as the static inner class.


package com.java8.examples;

public class Driver {
 enum SEX {
  MALE, FEMALE
 }

 private String name;
 private int age;
 private SEX sex;

 private Driver(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.sex = builder.sex;
 }

 
 @Override
 public String toString() {
  return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
 }

 //builder design pattern
 public static class Builder {
  private String name;
  private int age;
  private SEX sex;

  public Builder name(String name) {
   this.name = name;
   return this;
  }

  public Builder age(int age) {
   this.age = age;
   return this;
  }

  public Builder sex(SEX sex) {
   this.sex = sex;
   return this;
  }

  public Driver build() {
   return new Driver(this);
  }
 }
}


Now, here is how you elegantly construct the Driver object


package com.java8.examples;

public class DriverTest {
 
 public static void main(String[] args) {
  
   //immutable driver1 as Driver class has not setter methods
   Driver driver1 = new Driver.Builder()
             .name("John")
             .age(18)
             .sex(Driver.SEX.MALE)
             .build();
      
   System.out.println(driver1);
   
 }

}


Another example to create a list of drivers

package com.java8.examples;

import java.util.Arrays;
import java.util.List;

public class DriverTest {
 
 public static void main(String[] args) {
  List<driver> drivers = Arrays.asList (
  
   new Driver.Builder()
             .name("John")
             .age(18)
             .sex(Driver.SEX.MALE)
             .build(),
             
   new Driver.Builder()
             .name("Jessica")
             .age(24)
             .sex(Driver.SEX.FEMALE)
             .build(),
             
   new Driver.Builder()
             .name("Samantha")
             .age(36)
             .sex(Driver.SEX.FEMALE)
             .build()
                
   );   
    
 }

}



Another good practical example is Performing financial calculations with BigDecimal and Builder design pattern.

Labels:

Apr 15, 2014

Understanding dynamic proxies in Java with a practical example -- Service retry example

We earlier looked at  Java dynamic proxy class example --  Performance testing your Java application.

Design pattern: If you are asked to describe or talk about a design pattern, you could mention this dynamic proxy class as a proxy design pattern. Many pick either singleton or factory design pattern. It would be nicer to pick something other than these two common patterns. Some interviewers specifically ask you to pick anything except factory and singleton design pattern.

In real life applications, you need to retry services that fail. Let's us this retry service scenario to demonstrate dynamic proxy design pattern in Java.

Step 1: Create a dummy service to emulate an internal or external service with outage.


public interface DummyService {
     abstract void execute();
}


Step 2: The dummy service implementation that emulates failure every time except every 3rd call.

public class DummyServiceImpl implements DummyService {
 
 private int count = 0 ;
 
 public void execute() {
  count++;
  if(count % 3 == 0){
   System.out.println ("Executing service ............. ");
  }
  else {
   throw new RuntimeException("Service Cannot be accessed ..... ");
  }
 }

}




Step 3: Write a Retry service class using the dynamic proxy pattern, which acts as a proxy to retry services on its delegate i.e. DummyService. The service  invoker can specify the retry count.

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

public class RetryProxy<T> implements InvocationHandler {

 final T delegate; // underlying object
 int retryCount;

 //create a proxy
 public static Object newInstance(Object obj, int retryCount) {
  return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
    obj.getClass().getInterfaces(), new RetryProxy(obj, retryCount));
 }

 private RetryProxy(T underlying, int retryCount) {
  this.delegate = underlying;
  this.retryCount = retryCount;
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  int retries = 0;
  boolean completed = false;
  Object ret = null;

  while (!completed) {
   try {
    ret = method.invoke(delegate, args);
    completed = true;
   } catch (Exception e) {
    retries++;
    if (retries > retryCount) {
     completed = true;
     throw e;
    }
    System.out.println("Retrying the service. Retry count " + retries);
   }
  }

  return ret;

 }
}



Step 4: The test class to invoke the DummyService via its proxy.

public class DummyServiceInvocationTest {

 public static void main(String[] args) {
  DummyServiceInvocationTest test = new DummyServiceInvocationTest();
  test.method1();
 }

 public void method1() {
  DummyService service = (DummyService) RetryProxy.newInstance(new DummyServiceImpl(), 1);
  service.execute();
 }

}


Output:

Retrying the service. Retry count 1
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
 at com.sun.proxy.$Proxy0.execute(Unknown Source)
 at DummyServiceInvocationTest.method1(DummyServiceInvocationTest.java:13)
 at DummyServiceInvocationTest.main(DummyServiceInvocationTest.java:8)
Caused by: java.lang.reflect.InvocationTargetException
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:491)
 at RetryProxy.invoke(RetryProxy.java:28)
 ... 3 more
Caused by: java.lang.RuntimeException: Service Cannot be accessed ..... 
 at DummyServiceImpl.execute(DummyServiceImpl.java:12)
 ... 8 more


Increase the number of recounts to 3

 public void method1() {
  DummyService service = (DummyService) RetryProxy.newInstance(new DummyServiceImpl(), 3);
  service.execute();
 }



Output:


Retrying the service. Retry count 1
Retrying the service. Retry count 2
Executing service ............. 

Labels:

Sep 19, 2013

When to use a builder design pattern? real life tips

Interview questions relating to design patterns are very popular in job interviews. Even if  this topic is not covered in rare occassions, you can bring it up yourself to open-ended questions to impress your  interviewers.

Q. What are the key difference(s) between a factory and a builder design patterns?
A. The builder design pattern builds an object over several steps. It holds the needed state for the target item at each intermediate step. The  StringBuilder is a good example that goes through to produce a final string. Here is a real world example that shows how builders are used instead of constructors to create Immutable objects. Creating immutable objects where applicable is a development best practice.


The factory design pattern describes an object that knows how to create several different but related kinds of object in one step, where the specific type is chosen based on given parameters. 
Q. When would you use a builder design pattern?
A
  • To construct a complex object. For example, to construct XML DOM objects and any other hierachichal objects. You have to create plenty of nodes and attributes to get your final object.
  •  Builder pattern makes your code more readable as explained in the article  "Using Builders instead of Constructors to create Immutable objects". The article explains how you can create immutable objects in Java by using the builder design pattern as opposed to using multiple constructors, which is known as the "telescoping constructor anti pattern".Firstly, let's see what is not so elegant about using a constructor as shown below with a CashBalance object that takes 3 BigDecimal arguments. Then we will see how a builder class will make your code more intuitive. 

Q. Can you give some examples from your experience?
A.

Example 1: Custom class.





package com.myapp.data;

import java.math.BigDecimal;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.util.Assert;


public class NetAsset
{
    
    public static NetAsset EMPTY = new Builder().setGrossAssetValueBeforeTax(BigDecimal.ZERO)
            .setGrossAssetValueAfterTax(BigDecimal.ZERO).setTotalAssets(BigDecimal.ZERO)
            .setTotalInvestments(BigDecimal.ZERO)
            .setTotalLiabilities(BigDecimal.ZERO)
            .setTotalReceivables(BigDecimal.ZERO)
            .build();
    
    private final BigDecimal grossAssetValueAfterTax;
    private final BigDecimal grossAssetValueBeforeTax;
    private final BigDecimal totalReceivables;
    private final BigDecimal totalInvestments;
    private final BigDecimal totalAssets;
    private final BigDecimal totalLiabilities;
    
    // add more
    
    private NetAsset(Builder builder)
    {
        Assert.notNull(builder.grossAssetValueAfterTax);
        Assert.notNull(builder.grossAssetValueBeforeTax);
        Assert.notNull(builder.totalReceivables);
        Assert.notNull(builder.totalInvestments);
        Assert.notNull(builder.totalAssets);
        Assert.notNull(builder.totalLiabilities);
        
        this.grossAssetValueAfterTax = builder.grossAssetValueAfterTax;
        this.grossAssetValueBeforeTax = builder.grossAssetValueBeforeTax;
        this.totalReceivables = builder.totalReceivables;
        this.totalInvestments = builder.totalInvestments;
        this.totalAssets = builder.totalAssets;
        this.totalLiabilities = builder.totalLiabilities;
    }
    
    public BigDecimal getGrossAssetValueAfterTax()
    {
        return grossAssetValueAfterTax;
    }
    
    public BigDecimal getGrossAssetValueBeforeTax()
    {
        return grossAssetValueBeforeTax;
    }
    
    public BigDecimal getTotalReceivables()
    {
        return totalReceivables;
    }
    
    public BigDecimal getTotalInvestments()
    {
        return totalInvestments;
    }
    
    public BigDecimal getTotalAssets()
    {
        return totalAssets;
    }
    
    public BigDecimal getTotalLiabilities()
    {
        return totalLiabilities;
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
    
 
 //inner builder class
    public static class Builder
    {
        private BigDecimal grossAssetValueAfterTax;
        private BigDecimal grossAssetValueBeforeTax;
        private BigDecimal totalReceivables;
        private BigDecimal totalInvestments;
        private BigDecimal totalAssets;
        private BigDecimal totalLiabilities;
        
        // add more
        
        public Builder setGrossAssetValueAfterTax(BigDecimal grossAssetValueAfterTax)
        {
            this.grossAssetValueAfterTax = grossAssetValueAfterTax;
            return this;
        }
        
        public Builder setGrossAssetValueBeforeTax(BigDecimal grossAssetValueBeforeTax)
        {
            this.grossAssetValueBeforeTax = grossAssetValueBeforeTax;
            return this;
        }
        
        public Builder setTotalReceivables(BigDecimal totalReceivables)
        {
            this.totalReceivables = totalReceivables;
            return this;
        }
        
        public Builder setTotalInvestments(BigDecimal totalInvestments)
        {
            this.totalInvestments = totalInvestments;
            return this;
        }
        
        public Builder setTotalAssets(BigDecimal totalAssets)
        {
            this.totalAssets = totalAssets;
            return this;
        }
        
        public Builder setTotalLiabilities(BigDecimal totalLiabilities)
        {
            this.totalLiabilities = totalLiabilities;
            return this;
        }
        
        public NetAsset build()
        {
            return new NetAsset(this);
        }
    }
    
}


To use this class

  NetAsset.Builder builder = new NetAsset.Builder();
  builder.setGrossAssetValueBeforeTax(BigDecimal.valueOf("3500.00"))
         .setGrossAssetValueAfterTax(BigDecimal.valueOf("500.00"))
   .setTotalAssets(BigDecimal.valueOf("3500.00"))
         .setTotalReceivables(BigDecimal.valueOf("2500.00"));     


or

return NetAsset.EMPTY;


Example 2: The Mock objects library classes.

m.expects(once())
    .method("method1")
    .with(eq(1), eq(2))
    .returns("someResponse");


Example 3: The StringBuilder class.

  return new StringBuilder("initial text")
            .append("more text")
   .append("some more text").toString();



Example 4: Apache Camel route builders.

   private void configureJobSweeperRoute()
   {
         from(TIMER_START_UP)
              .routeId("JobRecovery")
              .delay(RECOVERY_JOB_KICKIN_DELAY)
              .log(INFO, "Start checking incompleted jobs on start up")
              .bean(recoveryService, "startUpJobRecovery")
              .end();

    }


So, it is very widely used.

Other design patterns - real life examples

Labels: