Saturday, November 22, 2014

Java Thread IV: BlockingQueue to Print Odd/Even Numbers

Today, we will see how to print odd even numbers using Blocking Queue.  

We want to print odd even numbers using two different threads and so it will obviously require some kind of thread synchronization to communicate while one thread is printing the number. So one thread will become producer (odd) and other one (even) will become consumer. Java provides BlockingQueue for thread synchronization in these kind of scenarios. 

BlockingQueue provides functions to support operations that awaits for the queue to become non-empty while retrieving elements or wait for the space to become available while inserting the elements.

In our example, we will use LinkedBlockingQueue which uses ReentrantLock (refer my earlier post) internally for thread synchronization. To implement the solution for our odd even thread, we will need two classes: TakeAndOfferNext class which is callable thread and OddAndEvenSignalling which will invoke the thread.

TakeAndOfferNext:

Now let's see the implementation of TakeAndOfferNext. We will need two blocking queues here: one for odd numbers and another one for even numbers.

    BlockingQueue takeFrom;
    BlockingQueue offerTo;

Blocking queue offers two synchronous operations called take() and offer(e). Take removes the element from the queue if it's non-empty and offer inserts to the queue if it's not full. Here, you dont' need to be aware of thread synchronization as blocking queue will take care of it through these two methods. So let's print odd even numbers using these blocking queues:

    public void print()    {
        while (true)  {
            try   {
                int i = takeFrom.take(); //removes the value in the "from" queue

                System.out.println(Thread.currentThread().getName() + " --> " + i);

                offerTo.offer(i + 1);    //increments the value by 1 and puts it in the "to" queue.

                if (i >= (maxNumber - 1)) {
                    System.exit(0);
                }
            } catch (InterruptedException e) {
                throw new IllegalStateException("Unexpected interrupt", e);
            }
        }
    }

As you can see here we are looping through the continuous loop until it reaches the max number. In the loop, we first take the first number (odd one) from the first queue and pass the next number (even one) to the another queue.

Okay, half work is done now how do we take even element from the another queue which we set at the end ? Well, we will need two threads to do this job which will switch the odde and even queues alternately in below class.

OddAndEvenSignalling:

        BlockingQueue odds = new LinkedBlockingQueue();
        BlockingQueue
evens = new LinkedBlockingQueue();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

Now, our two threads are ready to print odd and even numbers. So, let's pass it on to the TakeAndOfferNext class in such a way that it will switch odd and even queues in the print() method.

        executorService.submit(new TakeAndOfferNext(odds, evens, MAX_NUMBER));
        executorService.submit(new TakeAndOfferNext(evens, odds, MAX_NUMBER));

And that's it, your job is done !!!

Working code samples can be found here.


You can try producer consumer example using blocking queue as an exercise.

Monday, November 3, 2014

Java Design Patterns II: Command Pattern to get rid of ugly if else blocks in Java

In my career, I came across many legacy applications and code and saw many bizarre code samples because it has been served by many different programmers over the period and everybody was probably lazy or under pressure to meet the deadline !!!

I personally hate ugly code and have very bad habit of re-factoring it on the spot whether it's bad naming conventions, incorrect formatting, duplicate code or hard coded string literals etc. because I  cannot just read through it without that. One of the thing I observed constantly in all those applications was code duplication and abuse of if-else blocks. 


Many programmers just love if else blocks simply because it's convenient to satisfy business logic quickly. There is nothing bad in it because it's very common to have multiple conditional logic in your business requirements but it starts getting ugly when you try adjusting tens (or sometimes hundreds, yes that's right) of conditions in one method or class using if-else blocks. 


In one of my recent assignments, we had to write pseudo SWIFT parser to process trade instructions and convert SWIFT message to XML. It was obvious that we had to write Parser to convert all the SWIFT tags (around 200 tags) into XML after doing some processing on each of the swift tag. Here is the sample code we had in it's original form....



public void uglyMethodWithNastyIfElseBlocks(String tagName){
             
   if(tagName.equals("NetAmount")){
       System.out.println("Doing something with NetAmount and having value :32B:");
   } else if(tagName.equals("GrossAmount")){
      System.out.println("Doing something with GrossAmount and having value :32M:");
   } else if(tagName.equals("SecurityId")){
       System.out.println("Doing something with SecurityId and having value :35B:");
   }
   .
   .
   .
   .
   } else {
       System.out.println("No Tags Found");
   }
}

Now imagine you have around 100 odd tags and doing some of processing on all of them which are accommodated inside same method. So to avoid this kind of situations Java provides you Command Pattern.

Now, lets re-factor this class using Command Pattern. To achieve clean code we will need one interface TagValueProvider to define the command for each tag which is currently inside if-else blocks, Enumeration: TagEnumeration to define Tag properties and Mapper class to map Tags with it's concrete implementation:

TagValueProvider: Each tag with different  behavior will implement below command.

      public void processTag(TagEnumeration tag);

ReturnTagValueProvider: Concrete implementation of each command.

@Override
public void processTag(TagEnumeration tag) {
System.out.println("Doing something with "+ tag.NETAMOUNT.getTagName() +" and having value " + tag.NETAMOUNT.getTagValue());

}

TagEnumeration: Each tag will have it's own properties and so will be mapped in this enumeration.

NETAMOUNT("NetAmount", ":32B:"), //key value pair of tags
GROSSAMOUNT("GrossAmount", ":32M:"),

SECURITYID("SecurityId", ":35B:");

TagMapper:  Schema to map the tags with implementing class. So you can have multiple tags mapping with common class or separate class having specific implementation.


  public static Map tagSchemaMapper = new HashMap();

static {
tagSchemaMapper.put(TagEnumeration.NETAMOUNT, new ReturnNetAmount());
tagSchemaMapper.put(TagEnumeration.GROSSAMOUNT, new ReturnGrossAmount());
tagSchemaMapper.put(TagEnumeration.SECURITYID, new ReturnSecurityId());
}

Now, let's see how our ugly method will look like after this re-factoring in below case.

public void correctMethodWithCommandPattern(TagEnumeration tags){
TagMapper.tagSchemaMapper.get(tags).processTag(tags);
}

So as you can see your multiple if else blocks will be replaced with single statement since command for each tag is now moved to concrete classes.

This is much cleaner approach because you don't have to accommodate entire business logic in one single method and more importantly it provides more readability to the code since each tag will have it's concrete implementation.

Advantages:
Separate implementation of each command with interface.
Enumeration to define each tag and it's properties.
HashMap to map the tag with it's behavior.

Saturday, November 1, 2014

Java Desing Patterns I: Chain Of Responsibility For Trade Enrichment.

Sometime back in one of the interviews with top Investment Bank, I was asked to write top level design diagram and highlight Interfaces, Classes and important mehthods.

Below is the detailed problem statement:

1. Trade domain objects may be enriched to add further information.
2. There are many different types of enrichment which may be carried out on a trade. 
     Party & Booking enrichment are two specific types of Enricher.
3. All enrichment is done normally at certain point in Trade processing (e.g. multiple Enrichers operating sequentially on Trades). This must be done via single Enricher.
4. It may be important to control the order of some Enrichers.

This is smart question because it makes you think and touches upon few of basic core java concepts like: Open Closed principle, Program against interface and also your design pattern knowledge on Strategy & Chain Of Responsibility but most importantly it checks your analytical and designing skills.

I liked the question because it's smart, simple and yet tricky. It's much better than asking singltons & hashmaps and all those useless questions which are repeatedly asked over and over again and people still think knowing these concepts can only make them smart coders !!

Till, first two points, I was sure they are asking me to explain Strategy pattern and will be straight forward but when I read 3rd point, I was sure they are asking something tricky which needed to be done with combination of some design patterns.

After putting my analytical skills in action for couple of minutes, I realized they are indirectly asking me to implement Chain Of Responsibility to check my designing skills. So here is what I came up with:

We will mainly need one interface (TradeEnrichment) to define enrichment and two concrete implementations: BookingEnricher & PartyEnricher.

public interface TradeEnrichment {

public void enrichment(TradeAccount tradeAccount);

public void setNextEnricher(TradeEnrichment nextEnricher);

}

Here, second method is important because it will provide us order of execution. Now, let's see one concrete implementation of this interface as asked in the question.


public class BookingEnricher implements TradeEnrichment {


TradeEnrichment enricher;

@Override
public void enrichment(TradeAccount tradeAccount) {

System.out.println("Enriching The Trade Booked");

if(enricher != null)
this.enricher.enrichment(tradeAccount); // call next enrichment
}

@Override
public void setNextEnricher(TradeEnrichment nextEnricher) {
this.enricher = nextEnricher;
}

}

Here, I have provided dummy implementation of Booking enrichment. Important thing to note here is the last statement which calls next Enricher in the sequence. So after completing the job Enricher simply passes the call to next Enricher in the sequence set using setNextEnricher() method.

Now, using Strategy Pattern here we can make sure that TradeEnrichment can have any number of concrete implementations in future as required and so our design follows Open-Closed principle (Open for enhancement but closed for modifications)

We will also need one class to invoke all these components and control sequencing order for the Trades: EnrichmentProvider.


public class EnrichmentProvider {

TradeEnrichment firstEnricher;

public void EnrichmentProvider(){

this.firstEnricher = new BookingEnricher();
TradeEnrichment secondEnricher = new PartyEnricher();

/** 
* set enrichment sequence here. you may have N number of enrichers in                                futures and you can control 
* the order of sequence here without impacting actual implementation in                             TradeEnrichment.
*/
firstEnricher.setNextEnricher(secondEnricher);

}

public static void main(String[] args) {

EnrichmentProvider tradeEnrichmentProvider = new EnrichmentProvider();

TradeAccount account = new TradeAccount();
account.setTradeType(TradeType.BOOK);

tradeEnrichmentProvider.firstEnricher.enrichment(account);
}

}

As you can see we are controlling the order of enrichers in the constructor by setting the next enricher in the chain.

Interviewers were quite impressed with clear understanding or design concepts and ability to craft clean interfaces because it helps  to discuss problems in terms of design patterns during design sessions and building new softwares. You don't have to explain your team how you will set order, how you can keep your implementations open for enhancements but closed for modifications etc. All you need to tell them is use Strategy Pattern & Chain Of Responsibility for Trade Enricher to control the order here and your job as a manager or architect is done, provided, you have hired right tech resource !!!!

Working code can be found here.