Builder Design pattern in Java ? GoF design pattern

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java.

What problem Builder pattern solves in Java
What is builder design pattern in Java with exampleAs I said earlier Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Consider a class which is used to create Cake, now you need number of item like egg, milk, flour to create cake. many of them are mandatory and some  of them are optional like cherry, fruits etc. If we are going to have overloaded constructor for different kind of cake then there will be many constructor and even worst they will accept many parameter.

Problems:
1) too many constructors to maintain.
2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter.

You can partially solve this problem by creating Cake and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally cake should not be available until its created. Both of these problem can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed.

By the way there are many design pattern tutorial already there in Javarevisited like Decorator pattern tutorial and  Observer pattern in Java. If you haven’t read them already then its worth looking.

Example of Builder Design pattern in Java
We will use same example of creating Cake using Builder design pattern in Java. here we have static nested builder class inside Cake which is used to create object.

Guidelines for Builder design pattern in Java
1) Make a static nested class called Builder inside the class whose object will be build by Builder. In this example its Cake.

2) Builder class will have exactly same set of fields as original class.
3) Builder class will expose method for adding ingredients e.g. sugar() in this example. each method will return same Builder object. Builder will be enriched with each method call.

4) Builder.build() method will copy all builder field values into actual class and return object of Item class.
5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.

public class BuilderPatternExample {

    public static void main(String args[]) {
    
        //Creating object using Builder pattern in java
        Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5).  eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build();
    
        //Cake is ready to eat :)
        System.out.println(whiteCake);
    }
}

class Cake {

    private final double sugar;   //cup
    private final double butter;  //cup
    private final int eggs;
    private final int vanila;     //spoon
    private final double flour;   //cup
    private final double bakingpowder; //spoon
    private final double milk;  //cup
    private final int cherry;

    public static class Builder {

        private double sugar;   //cup
        private double butter;  //cup
        private int eggs;
        private int vanila;     //spoon
        private double flour;   //cup
        private double bakingpowder; //spoon
        private double milk;  //cup
        private int cherry;

        //builder methods for setting property
        public Builder sugar(double cup){this.sugar = cup; return this; }
        public Builder butter(double cup){this.butter = cup; return this; }
        public Builder eggs(int number){this.eggs = number; return this; }
        public Builder vanila(int spoon){this.vanila = spoon; return this; }
        public Builder flour(double cup){this.flour = cup; return this; }
        public Builder bakingpowder(double spoon){this.sugar = spoon; return this; }
        public Builder milk(double cup){this.milk = cup; return this; }
        public Builder cherry(int number){this.cherry = number; return this; }
    
    
        //return fully build object
        public Cake build() {
            return new Cake(this);
        }
    }

    //private constructor to enforce object creation through builder
    private Cake(Builder builder) {
        this.sugar = builder.sugar;
        this.butter = builder.butter;
        this.eggs = builder.eggs;
        this.vanila = builder.vanila;
        this.flour = builder.flour;
        this.bakingpowder = builder.bakingpowder;
        this.milk = builder.milk;
        this.cherry = builder.cherry;     
    }

    @Override
    public String toString() {
        return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}';

    }

}

Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}


Builder design pattern in Java – Pros and Cons

Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.

Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.

Disadvantages:
1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.

When to use Builder Design pattern in Java
Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.

That's all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go

xargs command example in Linux - Unix tutorial

xargs command in unix or Linux is a powerful command used in conjunction with find and grep command in UNIX to divide a big list of arguments into small list received from standard input. find and grep command produce long list of file names and we often want to either remove them or do some operation on them but many unix operating system doesn't accept such a long list of argument. UNIX xargs command divide that list into sub-list with acceptable length and made it work. This Unix tutorial is in continuation of my earlier post on Unix like 10 examples of chmod command in Unix and How to update soft link in Linux. If you haven’t read those unit tutorial than check them out. By the way In this tutorial we will see different example of unix xargs command to learn how to use xargs command with find and grep and other unix command and make most of it. Though what you can do with xargs in unix can also be done by using options provided in find but believe xargs is much easy and powerful.

Unix Xargs command example
Following is list of examples of xargs command which shows how useful knowledge of xargs can be. Feel free to copy and use this command and let me know if it didn’t work in any specific Unix operating system like AIX or Solaris.

Xargs Example 1- with and without xargs
in this example of xargs command we will see how output changes with use of xargs command in unix or Linux. Here is the output of find command without xargs first and than with xargs, you can clearly see that multiline output is converted into single line:

devuser@system:/etc find . -name "*bash*"
./bash.bashrc
./bash.bash_logout
./defaults/etc/bash.bashrc
./defaults/etc/bash.bash_logout
./defaults/etc/skel/.bashrc
./defaults/etc/skel/.bash_profile
./postinstall/bash.sh.done
./setup/bash.lst.gz
./skel/.bashrc
./skel/.bash_profile

devuser@system:/etc find . -name "*bash*" | xargs
./bash.bashrc ./bash.bash_logout ./defaults/etc/bash.bashrc ./defaults/etc/bash.bash_logout ./defaults/etc/skel/.bashrc ./defaults/etc/skel/.bash_profile ./postinstall/bash.sh.done ./setup/bash.lst.gz ./skel/.bashrc ./skel/.bash_profile


Xargs Example 2 – xargs and grep
Another common use fo unix xargs command is to first find the files and then look for specific keyword on that file using grep command. here is an example of xargs command that does it

find . -name "*.java" | xargs grep "Stock"

This will first find all java files from current directory or below and than on each java file look for word "Stocks"if you have your development environment setup in Linux or unix this is a great tool to find function references or class references on java files.

Xargs Example 3 – delete temporary file using find and xargs
Another common example of xargs command in unix is removing temporary files from system.

find /tmp -name "*.tmp" | xargs rm

This will remove all .tmp file from /tmp or below directory. xargs in unix is very fast as compared to deleting single file at a time which can also be done by using find command alone. By the way this is also a very popular Unix interview question.

Xargs Example 4 – xargs -0 to handle space in file name
xargs command examples in Unix and Linux - TutorialAbove example of xargs command in unix will not work as expected if any of file name contains space or new line on it. to avoid this problem we use find -print0 to produce null separated file name and xargs-0 to handle null separated items. Here is an example of xargs command in unix which can handle file name with spaces and newline:

find /tmp -name "*.tmp" -print0 | xargs -0 rm

Xargs Example 5 – xargs and cut command in Unix
Though most of xargs examples in unix will be along with find and grep command but xargs is not just limited to this two it can also be used with any command which generated long list of input for example we can use xargs with cut command in unix. In below example of unix xargs we will xargs example with cut command. for using cut command let's first create a .csv file with some data e.g.

devuser@system:/etc cat smartphones.csv
Iphone,Iphone4S
Samsung,Galaxy
LG,Optimus
HTC,3D

Now we will display name of mobile companies from first column using xargs command in one line:

devuser@system:/etc cut -d, -f1 smartphones.csv | sort | xargs
HTC Iphone LG Samsung

xargs Example 6 – command convert muti line output into single line
One more common example of xargs commands in Linux is by converting output of one command into one line. For example you can run any command and then combine xargs to convert output into single line. here is an example xargs in unix which does that.

devuser@system:~/perl ls -1 *.txt
derivatives.txt
futures.txt
fx.txt
options.txt
stock.txt
swaps.txt

devuser@system:~/perl ls -1 *.txt | xargs
derivatives.txt futures.txt fx.txt options.txt stock.txt swaps.txt


Xargs Example 7 - Counting number of lines in each file using xargs and find.
In this example of xargs command in unix we will combine "wc" with xargs and find to count number of lines in each  file, just like we did in our previous example with grep where we tried to find specific word in each Java file.

devuser@system:~/perl ls -1 *.txt | xargs wc -l
  0 derivatives.txt
  2 futures.txt
  0 fx.txt
  1 options.txt
  3 stock.txt
  0 swaps.txt

Xargs command Example 7 - Passing subset of arguments to xargs in Linux.
Some commands in unix can only work at certain number of argument e.g. diff command needs two argument. when used with xargs you can use flag "-n" to instruct xargs on how many argument it should pass to given command. this xargs command line option is extremely useful on certain situation like repeatedly doing diff etc. xargs in unix or Linux will continue to pass argument in specified number until it exhaust all input. here is an example of unix xargs command with limited argument:

devuser@system:~/perl ls -1 *.txt | xargs -n 2 echo
derivatives.txt futures.txt
fx.txt options.txt
stock.txt swaps.txt

In this example,  xargs is passing just two files at a time to echo as specified with "-n 2" xargs command line option.

Xargs example 9 - avoid "Argument list too long"
xargs in unix or Linux was initially use to avoid "Argument list too long" errors and by using xargs you send sub-list to any command which is shorter than "ARG_MAX" and that's how xargs avoid "Argument list too long" error. You can see current value of "ARG_MAX" by using getconf ARG_MAX. Normally xargs own limit is much smaller than what modern system can allow, default is 4096. You can override xargs sub list limit by using "-s" command line option.

Xargs Example 10 – find –exec vs find + xargs
xargs with find command is much faster than using -exec on find. since -exec runs for each file while xargs operates on sub-list level. to give an example if you need to change permission of 10000 files xargs with find will be almost 10K time faster than find with -exec because xargs change permission of all file at once. For more examples of find and xargs see my post 10 frequently used find command examples in Linux


Important points on xargs command in Unix and Linux
Now let’s revise some important points about xargs command in Unix which is worth remembering :

1. An important point to note about xargs is that it doesn't handle files which has newlines or white space in its name and to avoid this problem one should always use "xargs -0". xargs -o change separator to null character so its important that input feed to xargs is also use null as separator. for example gnu find command use -print0 to produce null separated file names.

2. Xargs command receives command from standard input which is by default separated with space or newlines and
execute those commands, you can still use double quotes or single quote to group commands.

3. If you don't give any command to xargs in unix, default command executed by xargs is /bin/echo and it will simply display file names.

4. One rare problem with xargs is end of file string, by default end of file string is "_" and if this string occurs in input the rest of input is ignored by xargs. Though you can change end of file string by using option "-eof".

5. Use man xargs or xargs --help to get help on xargs online while working in unix or Linux.

In short xargs command in Unix or Linux is an essential tool which enhances functionality of front line commands like find, grep or cut and gives more power to your shell script. These xargs command examples are good start for anyone wants to learn more about xargs command.Though these xargs examples are tested in Linux environment they will applicable for other Unix systems likes Solaris or AIX also. let us know if you face any issue while using these examples.

Debug java application in Eclipse by remotly

Remote debugging is not a new concept and many of you are aware of this just for who don’t know what is remote debugging? It’s a way of debugging any process could be Java or C++ running on some other location from your development machine.  Since debugging is essential part of development and ability to debug your application not only saves time but also increase productivity. Local debugging is the best way in my opinion and should always be preferred over remote debugging but if local debugging is not possible and there is no way to debug your process then remote debugging is the solution.
Many of us work on a project which runs on Linux operating system and we do development mostly on Windows. Since I am working in Investment banking and finance domain I have seen use of Linux server for running electronic trading application quite a lot, which makes development difficult because you don't have code running on your development machine.



Some time we managed to run the project in windows itself which is essential for development and debugging purpose but many times its not possible due to various reason e.g. your project depends upon some of the platform dependent library or some Linux module whose windows version may not be available or your project is too big to run on windows and its heavily connected to upstream and downstream system its almost impossible to create same environment in your windows machine for development.
On such situation my approach to work is isolate the work I am doing and test that with the help of mock objects, Threads or by trying to run that module independently but this is also not a desired solution in some cases where you need to debug the project at run time to find out some subtle issues.

Remote debugging in Java with Eclipse




Eclipse provides us most useful feature called "Remote debugging" by using which you can debug your Linux running process from your windows machine. believe me this become absolutely necessary in some condition and knowing how to setup remote debugging and working of remote debugging in eclipse can greatly improve your productivity. In this Eclipse tutorial I will try to explain eclipse remote debugging or how to setup remote debugging in eclipse.



Now let's see how we can setup remote debugging in Eclipse:

1) First setup your java project in Eclipse.

2) Select your project, go to "Run" Menu option and select "Debug Configurations"
remote debugging eclipse
Remote debugging with eclipse 1


3) This will open Debug Configuration window select "Remote Java Application" icon on left side, Right click and say "New".
How to do remote debugging in eclipse
eclipse remote debugging 2


4) After clicking on New, Eclipse will create Remote Java Application configuration for your selected project. Now next step is to setup host and port for remote debugging.
How to setup eclipse remote debugging
Remote debugging in Eclipse 3


5) Now put the host name and port on which your process is listening for debugger in Linux machine. Check the "Allow termination of remote VM" check box if you would like to close java application running on Linux from eclipse.

6) Now you are all set to remote debug your project. but before starting to debug make sure your java process is started with java debug settings and listening on same host and port, otherwise eclipse will not able to connect successfully.

7) To debug just click the "Debug" button in last screen where we have setup host and port.

8) You can also debug by going to "Debug Configurations" selecting your project in "Remote Java Application” and clicking on "DEBUG".



Java remote debug setting and JVM debug options
In order to remote debug a java application, that application must be started with following JVM debug options:

java -Xdebug -Xrunjdwp:transport=dt_socket,address=8001,server=y  suspend=y -jar stockTradingGUI.jar

This will start java applicaiton stockTradingGUI into debug mode using Java Debug Wire Protocol (jdwp) protocol and it will listen on port 8001
suspend=y will ensure that that application will not start running until eclipse connect it on speicified debug port.It also important to note
That application must be start before eclipse tries to connect it other wise Eclipse will throw error "Failed to connect to remote VM. Connection refused" or "Connection refused: connect"


Enjoy remote debugging in Eclipse J


Tip: In JVM DEBUG parameters there is a parameter called "suspend" which takes value as "y" or "n". so if you want to debug the process from start set this parameter as  "suspend=y" and your Java application will wait until Eclipse remotely connect to it. Otherwise if you want to run your program and later want eclipse to be connected that set this as "suspend=n" so your java application will run normally and after eclipse remotely connected to it, it will stop on breakpoints.


Tip: Use start up script to put JVM debug parameter and use a variable e.g. isDebugEnabled and also REMOTE_DEBUG_PORT in the script and export this variable when you want to remote debug your Java application. This will be very handy and will require just one time setup work.


Tip: if you get error "Failed to connect to remote VM. Connection refused" or "Connection refused: connect" then there might be two possibility one your java program is not running on remote host and other you are giving incorrect port or host name after verifying these two things if issue still persists then try giving full name of the host.

Tip: You also need to ensure that you run the same codebase in eclipse which is deployed in your remote machine so that what you debug and see in eclipse is true and real. you also need to ensure that your code is compile with debug option "-g" so that eclipse can easily gather debug info e.g. information about local variable. by default java only generate  line numbers and source file information.with  debug option -g your class file size might be more because it would contain some debug information.

Note: Recently I have wrote another article 10 tips on debugging Java Program in eclipse which is a collection of my java debugging tips and explains some advanced java debugging concept like conditional break point, how to debug multi-threaded programs in Java, Step filtering to avoid debugging system classes in Java, logical view to see the content of collection classes like HashMap or Arraylist in Java.


Latest HashSet Interview Question Related to Concept of working of HashSet

HashSet in Java is a collection which implements Set interface and backed by an HashMap. Since HashSet uses HashMap internally it provides constant time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order. Iterator of HashSet is fail-fast and throws ConcurrentModificationException if HashSet instance is modified concurrently during iteration by using any method other than remove() method of iterator class.If you want to keep insertion order by using HashSet than consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short correct understanding of HashSet is must for any Java developer.




Java HashSet Examples TutorialsIn this Java tutorial we will learn various examples of HashSet in Java and how to perform different operations in HashSet with simple examples. There is also a very famous interview questions based on HashSet is difference between HashMap and HashSet in java, which we have discussed in earlier post. You can also look that to learn more about HashSet in Java.


How to create HashSet object in Java
Creating HashSet is not different than any other Collection class. HashSet provides multiple constructor which gives you flexibility to create HashSet either copying objects from another collection, an standard way to convert ArrayList to HashSet. You can also specify initialCapacity and load factor to prevent unnecessary resizing of HashSet.


HashSet assetSet = new HashSet(); //HashSet instance without any element
HashSet fromArrayList = new HashSet(Arrays.asList(“Java”,”C++”)); //copying content
HashSet properSet = new HashSet(50); //HashSet with initial capacity




How to store Object into HashSet
Storing object into HashSet, also called elements is similar to Other implementation of Set, add() method of Set interface is used to store object into HashSet. Since Set doesn’t allow duplicates if HashSet already contains that object, it will not change the HashSet and add() will return false in that case.


assetSet.add("I am first object in HashSet"); // add will return true
assetSet.add("I am first object in HashSet"); // add will return false as Set already has




How to check HashSet is empty
There are multiple ways to check if HashSet is empty. An HashSet is called empty if it does not contain any element or if its size is zero. You can get size of HashSet as shown in further example and than see if its zero or not. Another way to do is by using isEmpty() method which returns true if underlying Collection or HashSet is empty.


boolean isEmpty = assetSet.isEmpty(); //isEmpty() will return true if HashSet is empty


if(assetSet.size() == 0){
    System.out.println("HashSet is empty, does not contain any element");
}

How to remove objects from HashSet in Java
HashSet in Java has nice little utility method called remove() remove object from HashSet. remove() deletes the specified object or element from this Set and returns true if Set contains element or false if Set does not contain that element. You can also use Iterator’s remove method for deleting object while Iterating over it.


assetSet.remove("I am first object in HashSet"); // remove will return true
assetSet.remove("I am first object in HashSet"); // remove will return false now


Iterator setIterator = assetSet.iterator()
while(setIterator.hasNext()){
   String item = setIterator().next();
   setIterator.remove(); //removes current element
}




How to clear HashSet in Java
HashSet in Java has a clear() method which removes all elements from HashSet and by clearing HashSet you can reuse It, only problem is that during multi-threading you need to be extra careful because while one thread is clearing objects form HashSet other thread can iterate over it.


assetSet.clear(); //clear Set, size of Set will be zero now


How to find size of HashSet in java
Size of HashSet returns number of objects stored in Collection. You can find size of HashSet by calling size() method of HashSet in Java. For an empty HashSet size() will return zero.


int size = assetSet.size(); // count of object stored in HashSet




How to check if HashSet contains an object
checking existence of an object inside HashSet in Java is not difficult, HashSet provides a utility method contains(Object o) for very same purpose. contains returns true if object exists in collection otherwise it returns false. By the way contains() method uses equals method to compare two object in HashSet. That’s why its important to override hashCode and equals method in Java.


assetSet.contains("Does this object exists in HashSet"); //contains() will return false
assetSet.add("Does this object exists in HashSet"); //add will return true as its new object
assetSet.contains("Does this object exists in HashSet"); // now contains will return true

How to convert HashSet into array in Java
HashSet has an utility method called toArray() inherited from Set interface. which is used to convert a HashSet into Array in Java see following example of converting hashset into array. toArray() returns an object array.


Object[] hashsetArray = assetSet.toArray();
Set<String> stringSet = new HashSet<String>();
String[] strArray = stringSet.toArray();


After Java 1.5 this method accept generics parameter and It can return the same type of element which is stored in HashSet. If size of Array is not sufficient than a new Array with runtime type of elements in HashSet is created. If you want to convert HashSet into Array List than search on Javarevisited.




That's all on this Java HashSet tutorial. HashSet in java is a one of the frequently used Collection class and can be very useful on certain scenario where you need to store unique elements with quick retrieval. important point to not about java HashSet it that add, remove, contains() and size() is constant time operation.

Junit Concept | Junit tutorial with example code

JUnit4 Annotations are single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations in Junit4,  creating and running a JUnit test becomes more easy and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of  JUnit 4 annotations and how to use them while writing JUnit tests. In this
Junit tutorial we will not only understand meaning of those annotations but also we will see examples of JUnit4 annotations. By the way this is my first post in JUnit 4 but if you are new here than you may like post 10 tips to write better code comments and 10 Object oriented design principles for Programmer as well.

JUnit 4 Annotations : Overview
Following is a list of frequently used JUnit4 Annotation , which is available when you include junit4.jar in your Classpath:

@Before
@BeforeClass
@After
@AfterClass
@Test
@Ignore
@Test(timeout=500)
@Test(expected=IllegalArgumentException.class)


@Before and @After
In Junit4 there is no setup() or tearDown() method and instead of that we have @Before and @After annotations.
By using @Before you can make any method as setup() and by using @After you can make any method as teardown(). What is most important point to remember is @Before and @After annotated method will be invoked before and after each test case. So in case you have five test cases in your JUnit test file than just like setup() and tearDown() method annotated with @Before and @After will be called five times. Here is an example of using
@Before and @After Annotation in JUnit4:

    @Before
    public void setUp() {
        System.out.println("@Before method will execute before every JUnit4 test");
    }

    @After
    public void tearDown() {
        System.out.println("@After method will execute before every JUnit4 test");
    }


@BeforeClass and @AfterClass
@BeforeClass and @AfterClass JUnit4 Annotations are similar to @After and @Before with only exception that they
are called on per TestClass basis and not on per test basis. They can be used as one time setup and tearDown
method and can be used to initialize class level resources. here is an example of using @BeforeClass and @AfterClass Annotations in JUnit4, here is an example of @BeforeClass and @AfterClass Junit 4 annotation

    @BeforeClass
    public static void setUpClass() throws Exception {
        System.out.println("@BeforeClass method will be executed before JUnit test for"
                + "a Class starts");
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
         System.out.println("@AfterClass method will be executed after JUnit test for"
                + "a Class Completed");
    }


@Test
@Test is a replacement of both TestCase class and convention "test" which we prefix to every test method. for example to test a method  called calculateInterest() we used to create method testCalcuatedInterest() and our class needs to be extended from org.junit.TestCase class. Now with @Test annotation that is not required any more. You just need to annotate your test method with @Test Junit4 annotation and done. no need to extend from TestCase class and no need to prefix "test" to your method, here is an example of  JUnit 4 @Test annotation

 @Test
    public void testCalculateInterest() {
        System.out.println("calculateInterest");
        fail("An Example of @Test JUnit4 annotation");
    }


@Ignore
JUnit 4 Annotations examples list meaningsSome time we add test method in JUnit test class but hasn't implemented that is causing your build to fail if JUnit testcase are integrated or embedded into build process. you can avoid that problem by marking your test method as @Ignore in Junit4. JUnit4 ignores method annotated with @Ignore and doesn't run during test. Here is an example of using @Ignore annotation in JUnit4 to exclude a particular Test from running:


 @Ignore("Not yet implemented")
    @Test
    public void testGetAmount() {
        System.out.println("getAmount");
        fail("@Ignore method will not run by JUnit4");
    }


@Test(timeout=500)
Now with JUnit4 writing testcases based on timeout is extremely easy. You just need to pass a parameter timeout with value in millisecond to @Test annotation. remember timeout values are specified in millisecond and your JUnit4 timeout test case will help if it doesn't complete before timeout period. This works great if you have SLA(Service Level Agreement)  and an operation need to complete before predefined timeout.

  @Test(timeout = 500)
    public void testTimeout() {
        System.out.println("@Test(timeout) can be used to enforce timeout in JUnit4 test case");
        while (1 == 1) {
        
        }
    }

This JUnit4 test will fail after 500 millisecond.

@Test(expected=IllegalArgumentException.class)
Another useful enhancement is Exception handling testcases of JUnit4. Now to test Exception is become very easy and you just need to specify Exception class inside @Test annotation to check whether a method throws a particular exception or not. here is an example which test behavior of a method to verify whether it throws Exception or not,  when run with invalid input:

    @Test(expected=IllegalArgumentException.class)
    public void testException(int input) {
        System.out.println("@Test(expected) will check for specified exception during its run");
    
    }


These were list of frequently used JUnit 4 annotations and there meanings. In the course we have also learn how to use @Before , @After in place of setup() and teardown(). Code review and Unit testing is one of the best development practices to follow and we must try our best to incorporate that in our daily coding and development cycle.

HashMap working concept in Java | how hashMap internally working

How HashMap works in Java or sometime how get method work in HashMap is common interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement

"Have you used HashMap before" or "What is HashMap? Why do we use it “

Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn't, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.
This shows that person has used hashMap and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like

"Do you Know how hashMap works in Java” or
"How does get () method of HashMap works in Java"

And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g

"What will happen if two different objects have same hashcode?”

Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
But story does not end here and final questions interviewer ask like

"How will you retreive if two different objects have same hashcode?”
 Hmmmmmmmmmmmmm
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.

So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer :)

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified
Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () method and there importance?
Benefit of immutable object?
race condition on hashmap in Java
Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions

How HashMAp works in Java
HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.
Also hashMap stores both key+value tuple in every node of linked list.

What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.






JDBC Database connection pool in Spring 2.5 Framework – Code setup in Spring for connection pooling

Setting up JDBC Database Connection Pool in Spring framework is easy for any Java application, just matter of changing few configuration in spring configuration file.If you are writing core java application and not running on any web or application server like Tomcat or  Weblogic,  Managing Database connection pool using Apache Commons DBCP and Commons Pool along-with Spring framework is nice choice but if you have luxury of having web server and managed J2EE Container, consider using Connection pool managed by J2EE server those are better option in terms of maintenance, flexibility and also help to prevent java.lang.OutofMemroyError:PermGen Space in tomcat by avoiding loading of JDBC driver in web-app class-loader, Also keeping JDBC connection pool information in Server makes it easy to change or include settings for JDBC over SSL. In this article we will see how to setup Database connection pool in spring framework using Apache commons DBCP and commons pool.jar

This article is in continuation of my tutorials on spring framework and database like LDAP Authentication in J2EE with Spring Security and  manage session using Spring security  If you haven’t read those article than you may find them useful.

Spring Example JDBC Database Connection Pool
Spring framework provides convenient JdbcTemplate class for performing all Database related operation. if you are not using Hibernate than using Spring's JdbcTemplate is good option. JdbcTemplate requires a DataSource which is javax.sql.DataSource implementation and you can get this directly using spring bean configuration or by using JNDI if you are using J2EE web server or application server for managing Connection Pool. See How to setup JDBC connection Pool in tomcat and Spring for JNDI based connection pooling for more details. In order to setup Data source you will require following configuration in your applicationContext.xml (spring configuration) file:
 
//Datasource connection settings in Spring
<bean id="springDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_TEST" />
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
   <property name="username" value="root" />
   <property name="password" value="root" />
   <property name="removeAbandoned" value="true"/>
   <property name="initialSize" value="20" />
   <property name="maxActive" value="30" />
</bean>

//Dao class configuration in spring
 <bean id="EmployeeDatabaseBean" class="com.test.EmployeeDAOImpl">
    <property name="dataSource" ref="springDataSource"/>
 </bean>


Below configuration of DBCP connection pool will create 20 database connection as initialSize is 20 and goes up to 30 Database connection if required as maxActive is 30. you can customize your database connection pool by using different properties provided by Apache DBCP library. Above example is creating connection pool with Oracle 11g database and we are using oracle.jdbc.driver.OracleDriver comes along with ojdbc6.jar or ojdbc6_g.jar ,  to learn more about how to connect Oracle database from Java program see the link.
Java Code for using Connection pool in Spring
Database connection pool Spring example codeBelow is complete code example of DAO class which uses Spring JdbcTemplate to execute SELECT query against database using database connection from Connection pool. If you are not initializing Database connection pool on start-up than it may take a while when you execute your first query because it needs to create certain number of SQL connection and then it execute query but once connection pool is created subsequent queries will execute faster.

//Code for DAO Class using Spring JdbcTemplate
package com.test
import javax.sql.DataSource;
import org.log4j.Logger;
import org.log4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Java Program example to use DBCP connection pool with Spring framework
 * @author Javin Paul
 */
public class EmployeeDAOImpl implements EmployeeDAO {

    private Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public boolean isEmployeeExists(String emp_id) {
        try {
            logger.debug("Checking Employee in EMP table using Spring Jdbc Template");
            int number = this.jdbcTemplate.queryForInt("select count(*) from EMP where emp_id=?", emp_id);
            if (number > 0) {
                return true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
}


Dependency:
1. you need to include oracle driver jar like ojdbc_6.jar in you classpath.
2. Apache DBCP and commons pool jar in application classpath.

That's all on how to configure JDBC Database connection pool in Spring framework.