Design Patterns

Design patterns are common practices which are used to solve problems which are similar in nature. More »

Algorithms and Data Structures

Data structures are basic building blocks of any computer program. Algorithms are used to solve any real life program programatically. More »

Java programming language

Java is one of the most popular and advanced programming language which is used to create many enterprise level solutions. More »

Fun Stuff

Kool and fun side of technology. More »

Other stuff

Random posts More »

 

Template method pattern vs Strategy Pattern

Template method pattern and Strategy pattern can appear quite similar in nature as both help us execute an algorithm/ code steps and define executions differently under different circumstances.

The major difference is that Strategy pattern let you decide complete different strategy i.e. set of algorithm(s) based on requirement at the run time, for example which tax strategy to be applied Indian or Chinese. On the other hand, Template pattern puts in some predefined steps (of a algorithm), out of which some are fixed and others can be implemented differently for different usages, say read data from file, parse data, write data to file- parsing might be done differently based on kind of data we are dealing with, but reading from and writing to file will be fixed.

More here -

http://kamalmeet.com/2013/03/understanding-strategy-pattern/
http://kamalmeet.com/2014/04/template-method-design-pattern/
http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-method-and-the-strategy-patterns

Template method design pattern

Template method design pattern allows one to create a template of code or algorithm which will provide guidelines for other developers on how to write the solution for different implementations.

To keep it simple, let’s go back to HTML template. HTML template lets you define overall look and feel of page without getting into details. For example, I want all my pages to have a header, a footer, left panel, right panel, middle content panel. I might want to add some parts are fixed, say header and footer will always looks same, but center, right and left can be customized by users.

Same principle is used in template design pattern. Say I have to implement a template reading data from database.

Step 1: get database connection
Step 2: create query
Step 3: Execute Query
Step 4: Parse Data
Step 5: Close connections

Here Step 1, 3 and 5 are common for all type of queries but Step 2 and 4 will be data dependent. This can be achieved by Template Method pattern.

A good explanation can be seen here

templatemethodpatternexample

Image from http://javapostsforlearning.blogspot.in/2013/03/template-method-design-pattern-in-java.html

Spring Framework- Basics

The question which I asked 4 years back when I was to use Spring framework for project was- Why Spring? I was using Struts for few years and was in love that, so why to try something new.

Over the time I have found a very convincing answer which I will share.

    1.Empowering POJO’s
    2.Dependency Injection
    3.It is more than web application development framework
    4.Support for Aspect oriented programming

1. For me most important feature which Spring provides is use of POJOs (Plain Old Java Objects). Working with frameworks like Struts, you need to follow a very strict format, for example for each controller servlet you need to extend action class and override execute method with fixed number of parameters. Even if you are creating simple servlet you need to have get and post methods to handle client requests in a particular format. Spring finally gives you freedom to use plain java classes and convert to controllers or request handlers using simple annotations.

2. Dependency injection is implementation of inversion of control principle which helps maintain loose coupling and move away dependencies from the current class and let it focus on its real goal. Read more on dependency injection-http://kamalmeet.com/2012/03/dependency-injection-simplified/, http://kamalmeet.com/2013/03/more-on-dependency-injection/, http://kamalmeet.com/2013/03/spring-implementation-of-dependency-injection/

3. As I said, Spring is not just for handling request response or implementing MVC like struts, it goes much beyond that. It is kind of a bouquet providing end to end solution for an application like it provides Spring Security for controlling access to application, provides Spring MVC for handling request/ response in MVC mode, provide Workflow to handle control flow, support for webservices through Spring Restful templates etc.

4. Finally support for aspect oriented programming (AOP). Spring supports AOP, that means you can separate some aspects of code so that your classes can focus on the responsibility given to them. For example creating logs is one aspect of a code, which we need to write in every class to make sure proper logs are maintained. Spring helps you pull this aspect out of the code and handle through some configuration making sure logging occurs whenever required.

Maximum Subarray Problem- N log N solution

For algorithm and explanation, read here.

Code implementation


public class MaxSumTest
{
/**
* Main method
* @param s
*/
public static void main(String s[])
{
int[] arr=new int[10];
arr=new int[]{10, -19 , 8 , 4, -5, 2, -1, 3, 8,-9};

int arrlength=arr.length/2;
int[] arr1=createarr(0,arrlength,arr);
int[] arr2=createarr(arrlength, arr.length,arr);
int sum=maxsum(arr1,arr2);
System.out.println(sum);
}

/**
* To find out maximum sum subarray, following divide and conquer technique is used
* 1. Divide the array in 2 equal parts, now there are 3 possibilities.
* a. Max sum subarray crosses the mid of original array, i.e. a part of solution is in left array and other in right. Finding this is simple as we just need to move backword on left subarray to find the maximum sum, and then move fwd on right array to find max, and finally add the two
* b. The other possibility is that max subarray is completely on left array. This means left subarray becomes main array and we discard right array. We will repeat the steps from 1.
* c. The last possibility is that max subarray is completely on right array. This means right subarray becomes main array and we discard left array. We will repeat the steps from 1.
*/
public static int maxsum(int[] arr1, int[] arr2)
{
int sum1=0;
int maxsum1=0;
int sum2=0;
int maxsum2=0;
int maxsum=0;

//1.a. Find maximum sum crossing the the mid of original array.
for(int i=arr1.length-1;i>=0;i–)
{
sum1=sum1+arr1[i];
if(maxsum1 }

for(int i=0;i {
sum2=sum2+arr2[i];
if(maxsum2 }
maxsum=maxsum1+maxsum2;

//1.b. Find maximum sum in left subarray
int arrlength=arr1.length/2;
if(arr1.length==1) return arr1[0];
if(arr1.length==2) return (max(arr1[0], arr1[1],0));
int[] arr11=createarr(0,arrlength,arr1);
int[] arr12=createarr(arrlength, arr1.length,arr1);

//1.c. Find maximum sum in right subarray
arrlength=arr2.length/2;
if(arr2.length==1) return arr2[0];
if(arr2.length==2) return (max(arr2[0], arr2[1],0));
int[] arr21=createarr(0,arrlength,arr2);
int[] arr22=createarr(arrlength, arr2.length,arr2);

//Repeat steps and return final max sum value
return max(maxsum, maxsum(arr11,arr12), maxsum(arr21,arr22));

}

/**
* Method to return max of 3 integers
* @param x
* @param y
* @param z
* @return
*/
public static int max(int x, int y, int z)
{
if(x>y)
if(x>z)
return x;
else
return z;
else
if(y>z)
return y;
else
return z;
}

/**
* Create a subarray from start to end
* @param start
* @param end
* @param arr
* @return
*/
public static int[] createarr(int start, int end, int[] arr)
{
int[] myarr=new int[end-start];
for(int i=start,j=0;i {
myarr[j++]=arr[i];
}
return myarr;
}
}

Finish.

eCommerce: A view from the backend

Apart from features mentioned in my last post, which were directly related to commerce part of business, following are other important parts of an ecommerce system

Content: Your system will need to display items like News on products, Stock prices, policies etc.The content might be product related like images or videos for promotion.

Community: For customer to make an educated guess, it is desirable that he should know what others are talking about product and services. Product reviews, comparisons, chat messages, forums can be helpful for this.

Some other features which are actually invisible to end users, but business needs to take care while setting up ecommerce system

Load Handling: How much concurrent load can your website handle? The ecommerce site needs to be load tested to understand its behavior with increasing load.

Scalability: The website today might be designed to handle 10K users, but in future we might have 100K users. Can our website (technology we used) will scale up to handle increased user base.

Search Engine Optimization (SEO): This is another important aspect of an ecommerce system. Say we have a website selling mobile phones. We would like to make sure that search engines rank our site high whenever a mobile related query like “Android smartphone”, “Nokia phone” etc is searched for.

To support all the features mentioned for ecommerce site, we need to have some services working at backend to fill in manage the data

Content management: How the content is to be managed on user interface. What all items will be displayed and their organization at UI. This means creation and maintenance of pages and templates to be shown on website.

Product management: To add and manage product details.

Catalog management: As mentioned earlier, catalog will create list of products in a categorized manner. There can be different version of catalogs created and maintained by business.

Order management (workflow): An order management process needs to be defined and maintained.

User management: This is for both end user (making purchase) and business user (managing the system). We need to make sure no one gets unauthorized access to the system. For end user we need to make sure if user is active, and maintain user purchase history.

Offers Management: Various offers are provided by business in form of discounts and personalized deals. Business needs to monitor these offers and when an offer is active (season based/ holiday season etc).

In addition to above mentioned components, a true ecommerce system might also have

Suppliers and supply chain management: From where we will get the products? How much inventory is available and how much time will it take to be delivered (or how many tickets are left).

Shipping management: How shipping is handled (mostly outsourced). How products which are returned to company are handled?

Customer Relationship management: How do we make sure customer keeps coming back. You need to maintain the customer purchase history so you can recommend the most suited products. Also returns and complaints needs to handled gracefully to avoid any bad publicity and encourage customer loyalty.

Key components of an eCommerce system

Having an online presence is a must for any business in current world. For a company which is selling products, it will mean creating an ecommerce website, from where customers can purchase products. There can be businesses which are selling totally online (Amazon, ebay) and others which already have offline selling mediums (showrooms), having ecommerce site as an additional way to sell products (Bestbuy).

Depending on the business, and role of ecommerce in it, and complexity of the system will vary. For example, one can have listing of products online but actual selling is through phone, or user can order online which is being manually interpreted by backoffice employees, or a completely automated system. There can be different types of ecommerce systems as well, some selling tangible products like mobile phones, electronics, apparels, other might be selling airline tickets, music for download, a consultant service etc.

As noted, we can have multiple types of ecommerce systems, but some of the key components used by most sites are-

Product Information: Product is the sellable unit in ecommerce system (we can sell services as well, but then they will be considered as product for that particular system). We need to have as much information as possible about product so that it can be shown to customer, who can then make an informed decision on purchase. Information should be provided in industry accepted standards, so that it can be compared easily by customer.

Catalog: A catalog is online version of brochure or menu, which should contain all the products (services) business is providing. The products are further categorized/ sub-categorized into meaningful lists like electronics > kitchen appliances > microwave

Search: This is most used feature of any ecommerce website. Rather then looking for a product in catalogs, customer will prefer searching for it by keywords. A  good search functionality will make sure he gets what he is looking for (or better).

Shopping cart: All the selected products by customer will be shown in shopping cart. This is responsible for applying any offers, taxes, discount etc.

User Details/ Profile management: An ecommerce site might allow a user to shop without login to system. But at times it is desirable to let user create a profile, so that he does not need to enter his details (address, name, phone number etc) everytime he makes a purchase.

Order management: How can customer order for a product or a service? Can he order online, send emails, call up customer care or go to nearby store.

Payment: What are different modes of payment customer can use- Credit card, debit card, net banking, cash on delivery etc. Usually a third party payment gateway can be used to keep focus on business requirements.

Guarantee/ Warranty management: A product might have guarantee or warranty associated, which needs to be honored by the business to make sure customer is coming back to it.

Offers: Businesses need to come up with frequent offers/ discounts/ loyalty programs to boost up sales. Business also uses techniques like cross sell or up sell to increase profit and help customer make good choices.

Privacy Policy: A business might need to collect some information from customer like name, address, age (sometimes more private info) etc. What will happen to info collected from customer (kept private)? Also will cookies be used by the site?

Security: Customer might be sharing sensitive information online, so system needs to use https/ SSL for data collection. Additional requirement will be to secure data already collected by use of authorization and firewalls.

Customizing Perspective in Eclipse

At times you might want to add items/ perspectives into eclipse menus and toolbars. For example, when I installed Android plugin into eclipse, I was not able to find Android SDK and SVD managers in my eclipse. To add these, I had to

Go To Window-> Customize Perspective-> Command Groups Availability

Eclipse

Synchronization: Object vs Class level

In my last post I wrote about how synchronization can help making sure that multiple threads do not execute same block of code at the same time. I will take the concept of synchronization a little further here. Going back to previous example.

public void test()
{
synchronized(this){
try {

count++;
Thread.sleep(1000);
System.out.println(“Hello from Runnable:”+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

synchronized(this) or using synchronized keyword at method level makes sure that no 2 threads execute the block of code at the same time. But there is a bit more to it. To elaborate, I have modified my test method slightly

public void test()
{
synchronized(this){
try {
count++;
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

And modified calling main method

public static void main(String s[])
{

Runnable r=new RunnableTest();
Runnable r2=new RunnableTest();

for(int i=0;i<20;i++)
{
Thread t1=new Thread(r);
t1.setName("1");
t1.start();

Thread t2=new Thread(r2);
t2.start();
t2.setName("2");
}
}

Now if I run this we will see something like

2 says Hello from Runnable:1
1 says Hello from Runnable:1
1 says Hello from Runnable:2
2 says Hello from Runnable:2
1 says Hello from Runnable:3
2 says Hello from Runnable:3

And if you will observe the output, it is appearing in pairs. So let us understand what is happening here.

First change, instead of one object of runnable we are using 2 objects, this is to basically highlight the behavior in synchronized(this) block. Second change is that I added name for thread so that we can print it out to understand which thread is actually executing.

Coming back to synchronized(this), look at the “this” keyword. “this” in Java refers to current object. So when we synchronize on this, it means we are synchronizing on current object, so as we are using two different objects, hence we see the behavior that two stream of threads is executing simultaneously in synchronized block. So we can say that with synchronized this, we make sure only one thread of the object is executing in synchronized block at a time.

Now there can be a situation where you want exactly one thread for whole class gets executed at a time, no matter if thread belongs to same object or not. There is a simple solution to it.

public void test()
{
synchronized(RunnableTest.class){ //Change this with class name
try {
count++;
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

There are other options for synchronization as well, not of much practical use (atleast I have not used them ever), but worth noting.

synchronized(“1″)

Remember, string is an object. So we are synchronizing based on a constant object here, which will make sure only one thread executes at a time, irrespective of class or objects. So for our example this will be same as synchronized(RunnableTest.class).

A more practical use can when we are trying to synchronizing a group of thread.

String key=Thread.currentThread().getName();
public void test()
{
synchronized(key){
try {
count++;
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Here I am using key to group threads based on which synchronization is done. The key here is simply name of thread, but it can be more realistic in real scenario.

Handling Multithreading with Synchronization

In last post I wrote about how can we speed up our processing using multiple threads in Java, basically doing parallel processing using threads. Using multithreading definitely helps speed up processing, but it can also result in corrupting data if not used properly. Let’s look at this example

//A simple Runnable class
public class RunnableTest implements Runnable{
int count=0;
public void test()
{
try {
count++;
Thread.sleep(1000); //This will just introduce some delay
System.out.println("Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void run() {
test();
}
}
and call it from somewhere like

Runnable r=new RunnableTest();

for(int i=0;i<20;i++)
{
Thread t1=new Thread(r);
t1.start();
}

Output:
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
..
..

We are calling run method 20 times which in turn calls test. We have deliberately introduced some delay in test to give it a feel of real method which is taking time to execute some statements. The output depicts that instead of count being printed as 1, 2, 3 and so on, it is 20 for all the calls. Which means that all the threads are trying to execute same block of code simultaneously. Though parallel processing of code is desirable behavior from multithreading, it can cause issues in scenarios mentioned above.

Let’s say in actual code we are trying to write data into a database. Instead of count we have ID. So first thread creates and ID as X. Then it does some processing and creates an insert statement. While it is doing the processing, a second thread starts executing the same code and creates another ID Y which overrides the ID X (same as count is being modified). So when our thread 1 reaches to the code where it is inserting the data, it will try inserting ID as Y (as X is overridden by Y). Then thread 2 comes and again try to insert ID Y, causing an error.

So in real world we can have blocks of code (or complete methods) which we want to make sure does not get executed by multiple threads at the same time. Fortunately Java provides a simple way to do this. The keyword is synchronized.

public void test()
{
synchronized(this){
try {

count++;
Thread.sleep(1000);
System.out.println(“Hello from Runnable:”+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Now if we run the same code, we will get

Hello from Runnable:1
Hello from Runnable:2
Hello from Runnable:3
Hello from Runnable:4
Hello from Runnable:5
Hello from Runnable:6

Synchronized block makes sure that only one thread is executing blocked code at a time. Another way to synchronize is define method itself as synchronized.

public synchronized void test()

This will make sure only one thread enters this method at a time.

Multithreading: Runnable vs Thread

What is multithreading? First of all let us understand what is thread? A thread is simply flow of control in a program/ process.

Now Let’s understand what is multithreading? Let’s take an example, there is a code which reads data from a file and uploads it to a database. Let’s say there are 10 such files and each file takes 1 hr to finish data upload. In a single threaded environment, it will simply translate to 10 hrs job as our code will read and upload files one by one.  Whereas when we move to multithreading, that is multiple threads are executing at the same time asynchronously, it will result in parallel processing of these files and the total time taken might be close to time taken by one file only.

Before getting into details lets understand how to implement multithreading in Java? There are 2 ways to achieve this.

1. Extend Thread class
public class ThreadTest extends Thread{

public void test()
{
System.out.println("Hello from Thread");
}
public void run()
{
test();
}
}

2. Implement Runnable interface

public class RunnableTest implements Runnable{
public void test()
{
System.out.println("Hello from Runnable");
}

@Override
public void run() {
test();
}
}

And somewhere in the main method

public static void main(String s[])
{
Thread t1=new ThreadTest();
t1.start();
Thread t2=new Thread(new RunnableTest());
t2.start();
}

As you can see the important method while using threads is “run”. This method gets called automatically by JVM whenever a thread starts.

Note that we do not call the run method directly, as that will be like calling a normal method and will wait for control to come back to calling class. Whereas using start will make sure the control flow continues without waiting for method call return. To understand what I am referring here, lets change the main method slightly

for(int i=0;i<20;i++)
{
Thread t1=new ThreadTest();
t1.start();
Thread t2=new Thread(new RunnableTest());
t2.start();
}

We will something like (no order)

Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable
Hello from Runnable
Hello from Thread
Hello from Thread
Hello from Thread
Hello from Runnable
Hello from Runnable

Now let’s change it to run

for(int i=0;i<20;i++)
{
Thread t1=new ThreadTest();
t1.run();
Thread t2=new Thread(new RunnableTest());
t2.run();
}

Output

Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable

So not actually using multithreading here.

Coming back to original example. Now you can see if we write the code for uploading the data from file to run method, and execute it in multithreaded fashion, we will be able to upload files simultaneously.

We have seen 2 ways to create threads in Java, one by extending thread class and other by implementing runnable. Which is better?

Usually we go for implementing runnable. When implementing runnable we can only override run method, and that is the only thing which we need in most of the cases. Whereas when we extent Thread, we can override other methods like start, sleep, stop etc, which is usually not required. Additionally, extending Thread has the obvious implementation that now our class cannot extend any other class (as Java allows only one class to be extended).