Thursday, December 25, 2014

How to create your own Unmodifiable List in Java ?

java.util.Collections class offers numerous utility methods, mostly static ones, to operate collection objects effectively.

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends. One of the most used utility from this class is unmodifiableCollections or lists.

 So today we will see how we can implement this feature using Java but before we go into more details; let's first understand what unmodifiableList offers to us.

Features:

Like UnmodifiableCollections it returns the wrapper object of the original list which is read-only view of original list. However, important thing to remember here is that it's not immutable list and so state of the object can be changed by modifying original list object.

For ex, any modification made to the original list will be visible to unmodifiable object reference as well.

So now let's see how we can achieve this features by our own custom implementations.

Implementation:

We will need two main classes: MyCollections class to provide the static method which will return our wrapper object and MyUnmodifiableList class which will be the wrapper here to be returned to the caller.

So as it's very much evidant from the API call that unmodifiableList method will be a static method

public class MyCollections {

    public final static  List unmodifiableList(final List list) {
        return (List) new MyUnmodifiableList(list);
    }
}


Since our static method returns the MyUnmodifiableList, we will need concrete implementation of this class. So what do we need from this class ??

1. It should be type of List in order to keep List reference.
2. It should maintain the reference to the original list since we will need to reflect the updates made to the original list.
3. It should not allow any modifications to this object.

So essentially it should behave like the way view does on database table .

To satisfy point #1 here, we will need to implement List interface so class definition will become like this...

public class MyUnmodifiableList implements List {

Now, to get point #2 right,  will need to have List reference in the class;

    List originalList;


Remember, this variable has to keep reference to the originalList and so you might start getting confused now because you kept hearing this whole your life that "java is pass by value and not by reference". Then how on the earth you can keep the reference here to the original List !!

Well, everything you heard is right that Java is pass by value only but in case of objects, it passes the object reference by the value and so any change in original list will still reflect in MyUnmodifiableList reference. Excellent, so we are almost there.....

So last but not least, for point #3, all you need is to keep this class Immutable as the definition says and so what are the methods which can change your object state ??

To name few: add(), addAll(), remove(), removeAll() and few more. Yes, will need to override all of List interface methods here and so you'll need to update it accordingly so that it doesnt support the object state to change.


    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }


So finally we are done now as we have satisfied all of the above conditions and requirements mentioned above for the unmodifiableList interface.

Why I chose this particular example is because it checks lot of core concepts of Java & OOPS. So if you carefully observe this example, it touched upon OOPS (List interface), Program against Interface, Composition over inheritance, Pass by value or reference , Immutable Objects, Exception Handling etc......

If you could implement or understand this example means, you know all of this concepts and  ready to touch upon some more complex examples.

So keep reading.........................................!!!!



Tuesday, December 23, 2014

Java Reflection for Enumerations


Enumerations are pretty handy when it comes to define your own schema for static fields and we all know the power of enumerations so I'm not going to discuss more about enumerations here as you would find many blogs and articles on it.

Today, we are going to discuss the use case where we will need to use enumerations to provide dynamic validations on input fields using reflection and also will see bit more complex example where will need to use reflection to invoke enumeration itself.

Problem Statement: 

Suppose you are receiving the input as CSV file and need to validate all the input fields based on below criteria:
- Field should be validated based on max length.
- Field should be validated based on access types: mandatory or optional.
- Field should be validated based on data type: alphanumeric, numeric (decimal), date etc.

Now, in order to satisfy above requirements, obvious way one would think of is to put if else blocks on each input fields and validate all of above criteria.

Well, nothing wrong with that but it's a old fashioned or rather cruel way of doing things. Java provides many robust features after 1.5 version onwards and we should leverage it.

So, closely observing above requirements you can see we need two static schemas at first: Data type & Access type which can be defined as given below.

public enum DataTypes {
    ALPHANUMERIC, NUMERIC, DATE, STRING;
}


public enum AccessTypes {
    OPTIONAL, CONDITIONAL, MANDATORY;
}

Now using above schema, we want to define the CSV schema for the field validations.

public enum CSVFieldEnumerations {
    ESCROW_ACCOUNT(0, "escrowAccount", "Escrow Account", DataTypes.ALPHANUMERIC, 12 , 0, AccessTypes.MANDATORY),
    CURRENCY(1, "currency", "Currency", DataTypes.ALPHANUMERIC, 3, 0, AccessTypes.MANDATORY),
    PRINCIPAL(2, "principal", "Principal", DataTypes.NUMERIC, 17, 2, AccessTypes.MANDATORY),
    START_DATE(3, "startDate", "Start Date", DataTypes.ALPHANUMERIC, 8, 0, AccessTypes.MANDATORY);


    private int columnNumber;
    private String columnName;
    private String columnDescription;
    private DataTypes columnType;
    private int maxLength;
    private int decimalPlaces;
    private AccessTypes accessType;

    private CSVFieldEnumerations(int columnNumber,
                                    String columnName,
                                    String columnDescription,
                                    DataTypes columnType,
                                    int maxLength,
                                    int decimalPlaces,
                                    AccessTypes accessType) {   
       
        this.columnNumber = columnNumber;
        this.columnName = columnName;
        this.columnDescription = columnDescription;
        this.columnType = columnType;
        this.maxLength = maxLength;
        this.decimalPlaces =  decimalPlaces;
        this.accessType =  accessType;
    }  
 }


Suppose we are using the CSVParser class to read the CSV and validate all input values.JDK provides special Set & Map interfaces to iterate through the enums: EnumSet & EnumMap. We will be using EnumSet here to iterate over the enumerations defined here.

        for (CSVFieldEnumerations schema: EnumSet.allOf(CSVFieldEnumerations.class)) {
Now, lets see how we can utilize the schema to provide the dynamic validations. We will create static methods to access these dynamic properties and provide validations.

    public final static String validateAlphaNumericField(CSVFieldEnumerations column, String value) {
        if(StringValidation.checkLength(value, column.getMaxLength())) {
             if(!StringValidation.isAlphanumeric(column.getColumnName())) {
                 return column.getColumnDescription() + " is not an alphanumeric value";
             } else {
                 return null;
             }
        } else {
            return "Mandatory field " + column.getColumnDescription() + " exceeds size " + column.getMaxLength();
        }
    }


As you can see here, we are accessing the schema values using the enumerations to do validations here.


So we have used the schema to do dynamic validations but we also want to create CSVRecord object from the raw input data and our enumeration will do that as well for us. Remember we have defined columnName in our schema which will be the field name of CSVRecord object.

Reflection:

Field field = CSVRecord.class.getDeclaredField(schema.getColumnName());
setterMethod = CSVRecord.class.getMethod("set" +   StringUtils.capitalize(schema.getColumnName()), (Class) field.getType());
setterMethod.invoke(result, currentColumn.trim());


So here we will iterate through the EnumSet for each enumeration constants defined in the schema and will validate based on the metadata defined along with setting up the CSVRecord Object.  

So two birds with single stone !!
This is the power of Enumeration when combined with Reflection.

Reflection to load Enumerations:

Now, let's make above example bit more complex and consider the scenario where you need one more layer to load enumerations itself using the reflection.

Say, you have 4 different CSVs to parse and prepare common CSVRecord to send out as XML. so one will say what's the big deal, I'll set the CSV type in the parser and then will use  that to load enumeration and then iterate it over using EnumSet like we did above.

Well, here is the catch, while you fetch the enumeration using EnumSet.allOf(), you need to cast it to perticular enumeration but here you don't have any type to cast unless you do it in if else blocks for each enumeration defined for the CSV type because Enumerations cannot subclassed and so you dont' have supertype here.

Well, alternately you can use generics to load enumerations using the reflection as given here.

        Class enumClass = Class.forName("com.csv." + this.csvTypes);
        Object[] enumConstants = enumClass.getEnumConstants();

        for (int i = 0; i < enumConstants.length; i++) {
            Class sub = enumConstants[0].getClass();              
            enumColumnName = sub.getDeclaredMethod("getColumnName");
            columnNameValue = String.valueOf(enumColumnName.invoke(enumConstants[i]));
          .

          .
          .
          .
         
 So, here we are using '?' since we don't know the type of the returned enumeration but still able to invoke the getters on the enum properties to achieve the desired results !!

Hope, this will help you understand enumerations and refection concepts.

so happy reading......





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.

Friday, October 31, 2014

Java Thread III: Producer Consumer Using Synchronization vs Locks

Producer Consumer has always been favorite question in java multi-threading interviews.

We will create threads using two ways: Using usual synchronization & Locks.

Synchronization:\

Synchronization is standard way of locking shared resources and provide multi-threading. We  will create here two inner classes: Producer & Consumer and will use Stack to share the resources.

Producer:

class Producer extends Thread {


@Override
public void run() {
while (true) {
synchronized (itemStack) {
if (itemStack.size() <= MAX) {
COUNTER++;
itemStack.push(String.valueOf(COUNTER));
System.out.println("producing item ->" + COUNTER
+ " & size of stack is now :: "
+ itemStack.size());
itemStack.notifyAll();
}

while (itemStack.size() == MAX) {
try {
System.out.println("Stack is full & Producer is waiting.");
itemStack.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

}

Consumer:

private class Consumer extends Thread {


@Override
public void run() {
while (true) {
synchronized (itemStack) {
if (itemStack.size() != EMPTY) {
System.out.println("Consuming item ->"
+ itemStack.pop()
+ " & size of stack is now :: "
+ itemStack.size());
itemStack.notifyAll();
}g

while (itemStack.size() == EMPTY) {
System.out.println("Stack is empty & Consumer is waiting.");
COUNTER = 0;
try {
itemStack.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

}

As you can see here, we are trying to acquire the lock using synchronization on shared object Stack.

NOTE: Make sure you declare itemStack as static variable or else both threads will deadlock each other.

Working code can be found here.

Lock:

Now let's see how we can rewrite same example using ReentrantLock object which is provided in java.util.concurrent package in jdk 5.


Please see my earlier post on Reentrant Lock if you are new to Lock concepts.

To rewrite producer consumer example using Lock, we will need below piece of code.

    private static Lock lock = new ReentrantLock();
    private static Condition hasSpace = lock.newCondition();
    private static Condition hasItems = lock.newCondition();

First line will create explicit lock object for our example and rest of two lines will provide the conditions required to synchronize the Stack.

Condition objects provides await(), signal() & signalAll() methods similar to wait(), notify() and notifyAll() provided by Object class.

Now, Lets see how we can leverage all of this in our example below.

private class Producer extends Thread {

@Override
public void run() {
while (true) {
try {
lock.lock();
while (itemStack.size() >= MAX) {
System.out.println("Stack is full & Producer is waiting.");
try {
// wait for the list to have space
hasSpace.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

COUNTER++;
itemStack.push(String.valueOf(COUNTER));
System.out.println("producing item number -> "
+ itemStack.size());
hasItems.signalAll();

} finally {
lock.unlock();
}
}
}
}

private class Consumer extends Thread {

@Override
public void run() {
while (true) {
try {
lock.lock();
while (itemStack.size() == EMPTY) {
System.out.println("Stack is empty & Consumer is waiting.");
try {
COUNTER = 0;
// wait for the list to have space
hasItems.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
itemStack.pop();
System.out.println("consuming item number -> "+ itemStack.size());
hasSpace.signalAll();
} finally {
lock.unlock();
}
}
}

}

So As you can see now,  we are acquiring the lock explicitly at the beginning of run() method and releasing it in finally block. Also, lock object provides separate conditions for Producer & Consumer objects as well and simplifies the code further because you know here which condition should await and which one should be signaled. (Check synchronized version for wait & notify conditions to compare against).

It provides more readability to synchronization code since now you have separate object for locking and so you know what exactly you are synchronizing on. In synchronized version, remember, we were relying on Stack object for locking and sometime this can lead to more confusion and can create deadlocks as well. (Hint: try synchronized version with Stack object as non-static reference.)

However, here since locking is explicit, you need to be alert to unlock the lock object at the end of it can create issues later in the code.

Working code can be found here.

Hope, this will help you understand synchronization and locking concepts.

Thursday, October 30, 2014

Java Thread II: Reentrant Lock Vs Synchronized

Today we will see the difference between Lock and Synchronized block but before we go into details, let's understand what is Lock and how it works.

What is Lock ?

Lock interface was introduced in jdk 1.5 along with other concurrency utilities like countdown latch etc. ReentrantLock is the main concrete implementation of lock interface which behaves as mutually exclusive lock like synchronized block.
So the next question comes in mind is why, or most importantly when, one should prefer Lock when we already have synchronized. There are some trade offs between these two and Reentrant Lock can be used in couple of conditions.
For example, Lock provides explicit locking and so it has more readability comparing to synchronized. You will see this in below examples.

1. Fairness:

The ReentrantLock constructor offers a choice of two fairness options: create a non-fair lock or a fair lock. With fair locking, threads can acquire locks only in the order in which they were requested, whereas an unfair lock allows a lock to acquire it out of its turn. This is called barging (breaking the queue and acquiring the lock when it became available).

Fair locking has a significant performance cost because of the overhead of suspending and resuming threads. There could be cases where there is a significant delay between when a suspended thread is resumed and when it actually runs. Let's see a situation:

A -> holds a lock.
B -> has requested and is in a suspended state waiting for A to release the lock.
C -> requests the lock at the same time that A releases the lock, and has not yet gone to a suspended state.

As C has not yet gone to a suspended state, there is a chance that it can acquire the lock released by A, use it, and release it before B even finishes waking up. So, in this context, unfair lock has a significant performance advantage.

2. Polled and Timed Lock Acquisition: 

Let's see some example code:

public void transferMoneyWithSync(Account fromAccount, Account toAccount,
   float amount) throws InsufficientAmountException {
  synchronized (fromAccount) {
   // acquired lock on fromAccount Object
   synchronized (toAccount) {
    // acquired lock on toAccount Object
    if (amount > fromAccount.getCurrentAmount()) {
     throw new InsufficientAmountException(
       "Insufficient Balance");
    } else {
     fromAccount.debit(amount);
     toAccount.credit(amount);
    }
   }
  }
 }

In the transferMoney() method above, there is a possibility of deadlock when two threads 

A and B are trying to transfer money at almost the same time.
A: transferMoney(acc1, acc2, 20);
B: transferMoney(acc2, acc1 ,25);

It is possible that thread A has acquired a lock on the acc1 object and is waiting to acquire a lock on the acc2 object. Meanwhile, thread B has acquired a lock on the acc2 object and is waiting for a lock on acc1. This will lead to deadlock, and the system would have to be restarted! There is, however, a way to avoid this, which is called "lock ordering." Personally, I find this a bit complex. 

A cleaner approach is implemented by ReentrantLock with the use of tryLock() method. This approach is called the "timed and polled lock-acquisition." It lets you regain control if you cannot acquire all the required locks, release the ones you have acquired and retry. 

So, using tryLock, we will attempt to acquire both locks. If we cannot attain both, we will release if one of these has been acquired, then retry

public boolean transferMoneyWithTryLock(Account fromAccount,
   Account toAccount, float amount) throws InsufficientAmountException, InterruptedException 
{
 // we are defining a stopTime
 long stopTime = System.nanoTime() + 5000;
 while (true) {
  if (fromAccount.lock.tryLock()) {
    try {
   if (toAccount.lock.tryLock()) {
       try {
      if (amount > fromAccount.getCurrentAmount()) {
     throw new InsufficientAmountException(          "Insufficient Balance");
       } else {
     fromAccount.debit(amount);
     toAccount.credit(amount);
       }
    } finally {
       toAccount.lock.unlock();
    }
    }
      } finally {
   fromAccount.lock.unlock();
      }
  }
 if(System.nanoTime() < stopTime)
    return false;
    Thread.sleep(100);
 }//while
 }

Here we implemented a timed lock, so if the locks cannot be acquired within the specified time, the transferMoney method will return a failure notice and exit gracefully. We can also maintain time budget activities using this concept. 


3. Interruptible Lock Acquisition:

Interruptible lock acquisition allows locking to be used within cancellable activities.
The lockInterruptibly method allows us to try and acquire a lock while being available for interruption. So, basically it allows the thread to immediately react to the interrupt signal sent to it from another thread. 

This can be helpful when we want to send a KILL signal to all the waiting locks. Let's see one example: Suppose we have a shared line to send messages. We would want to design it in such a way that if another thread comes and interrupts the current thread, the lock should release and perform the exit or shut down operations to cancel the current task.

public boolean sendOnSharedLine(String message) throws InterruptedException{
  lock.lockInterruptibly();
  try{
   return cancellableSendOnSharedLine(message);
  } finally {
   lock.unlock();
  }
 }
private boolean cancellableSendOnSharedLine(String message){
.......

4. Non-block Structured Locking:

In intrinsic locks, acquire-release pairs are block-structured. In other words, a lock is always released in the same basic block in which it was acquired, regardless of how control exits the block. Extrinsic locks allow the facility to have more explicit control. Some concepts, like Lock Strapping, can be achieved more easily using extrinsic locks. Some use cases are seen in hash-bashed collections and linked lists.

private ReentrantLock lock;
public void foo() {
  ...
  lock.lock();
  ...
}
public void bar() {
  ...
  lock.unlock();
  ...
}

Intrinsic locks and extrinsic locks have the same mechanism inside for locking, so the performance improvement is purely subjective. It depends on the use cases we discussed above. Extrinsic locks give a more explicit control mechanism for better handling of deadlocks, starvation, and so on

When should you use ReentrantLocks? 

The answer is pretty simple - use it when you actually need something it provides that synchronized doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use ReentrantLock.

Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.