Monday, March 1, 2010

Introduction to Cloud Computing and Software as a Service (SaaS)

Introduction
Around 1960, after successfully installed the 1st packet switching based network (ARPANET), J.C. R. Licklider envisioned the concept of ‘Intergalactic Computer Network’ where the globe can be encircled by the complex net of all computers in the world. In the same era, John McCarthy, introduced the concept of utility computing in which computer can be used like other utilities for e.g. electricity, telephone etc. These two visionary concepts put the foundation of what is better known today as Cloud Computing.
This article is written with an aim to introduce the concept of cloud computing and explore in depth one of its widely accepted and useful model i.e. Software as a Service (SaaS).

Cloud Computing
Cloud Computing is a concept in which computing resources are made available on the internet and consumed by the clients as a demanded service. In-line with the other concepts in computing like grid, distributed and utility computing, cloud computing is a concept and different people have explained, defined and implemented it in different ways, but one of the best definition which could comprehensively defined cloud computing is


“Cloud Computing is the provisioning of dynamically scalable and often virtualized computing resources as demanded services over the internet”


Cloud computing has 3 major variant or models depending on the resources being exposed as service to the client. These are briefly defined below.


Platform as a Service (PaaS): In this model, the development platform is made available to the clients as demanded service over internet. The software, development and testing tools, configuration management tools, databases and all other required tools and APIs are provided by vendor in their environment. Developers can create, deploy and test the product in the provider’s platform. One of the best examples is the services provided by sales force (www.salesforce.com/platform)
Infrastructure as a Service (IaaS): In this model the complete IT infrastructure is made available in cloud as demanded services. This includes varieties of hardware, heterogeneous OS, globally distributed environments, commonly used enterprise solutions like HR, Payroll etc, data storage along with services like data security, authentication/authorization, backups, upgrade etc. Amazon’s Elastic Compute Cloud (EC2) is a good example of this category.
Software as a Service (SaaS): The most useful and wide accepted model in cloud computing is Software as a Service. In this model the software is exposed as demanded service over the cloud. Below section describe this model in depth along with its critical characteristics.

Software as a Service (SaaS)
Software as a Service model is a beautiful bouquet in which the concepts are picked up from different areas including Application Service Provider (ASP), hosted Solutions, Utility Computing, Virtualization and many more.
In SaaS model, vendor expose centrally managed software as on-demand service to the clients over Internet. This is against the orthodox in-premise or distributed model in which vendor distribute and install software in client’s environment and made it locally available.
SaaS model can further be understood by considering its top 10 characteristics†.

  1. Service Oriented Architecture (SOA): One of the important properties of any cloud computing model is ‘service’. In SaaS model the software is exposed as a service to the customer. This necessitates the adoption of service oriented architecture in the application.
  2. Hosted Environment: SaaS solutions are more often managed centrally and made available in hosted environment rather than at each client’s location.
  3. Virtualization: SaaS solutions should be deployed in virtual environment to support scalability, smooth upgrade and decoupling with underlying hardware.
  4. Multi-tenancy: SaaS solutions are believed to be deployed using multi-tenancy architecture where single application instance and data model is shared within multiple clients.
  5. Provisioning and Metering: SaaS solution should be provided with easy mechanism for tenant provisioning and metering the usage of the services.
  6. Service Elasticity: SaaS solution is said to be on-demand based services. Which means client should be able to use as little or as much as services as the business needs.
  7. Scalability: As SaaS solutions are deployed globally and provide elastic services, scalability becomes an essential characteristic of such solutions. More often, such solutions are deployed in cluster of virtualized server which can be add/remove services to meet the demand.
  8. Upgradability: SaaS solution should be provided with centralized easy upgradability. This include software and hardware upgradability.
  9. SLA Driven: SaaS solutions are driven by coherent licensing agreement based on per user per access basis.
  10. Availability and Self Healing: SaaS solutions are committed to provide complete availability and with failover mechanism. In case of failure, there will be a hot backup instance of the application ready to take over without disruption.
† Note that most of these characteristics are common for all models of cloud computing and hence can also be read as characteristics of cloud computing model.

Advantages of SaaS Model
SaaS solution uses multiple concepts and ideas to provide low cost business solutions. Some of the notable advantages associated with SaaS model are listed below.

  1. SaaS provide low cost solution. Businesses can obtain licenses to use software as per need basis.
  2. Customers can use service on pay-for-what-you-need basis depending on business needs.
  3. SaaS model avoid overhead of managing IT resources including software and hardware resources and hence facilitate organization to focus on the business.
  4. SaaS being web-native, thin clients like browsers may be used to access the software. Hence further reduces the cost at client end.
  5. SaaS solutions can easily be integrated with available business solutions at client end.
  6. SaaS solutions are scalable and virtualized. Providers can increase decrease the servers depending on service demand without changing the software architecture.
  7. Being designed in multi-tenant architecture, SaaS solution enables multiple customers and users to access the shared application and data model.

Challenges with SaaS Model:
Although SaaS model has many advantages to the business, it comes with few challenges as well which are listed below.

  1. As SaaS model is centrally managed and made available in hosted environment, it requires organizations to make valuable business data available in cloud, which could be a major threat.
  2. Security, integrity and reliability of critical business data is in vendor’s hand.
  3. Being a network-based access, the availability of a SaaS solution is subjected to network availability.
  4. Performance can be an issue as all request goes through cloud.
  5. One of the major concerns with this model is that not all software can be exposed as services.
  6. The last, but an important point is related with the fine terms and conditions mentioned in the agreement, which may be dangerous to the business sometimes. An article mentioning some of these terms is available here: http://webworkerdaily.com/2008/07/03/who-owns-your-online-documents/

Conclusion
Cloud Computing exposes computing resources (hardware and software) and services over internet as demanded services which help organizations by providing low cost IT solutions. Software as a Service model enables clients to use software as services over cloud and pay as per the usages. SaaS eliminates the need for software installation and maintenance at the client end and allows organizations for focus on core business activities.

About the Author
Ashish Arya has more than 7 years of experience in architecture and designing enterprise solutions using open source J2EE technologies. He also actively involved in designing SaaS solutions for banking and financial institutes.

Thursday, March 6, 2008

Unit Test Driven Development Approach

  1. Introduction
    It is one of the best practices in software industry to adopt standard methodologies and approaches in every phase of SDLC. Development, being the most critical phase, should also be accompanied by standard and approved methodology. A standard methodology is based on some theme factor which drives the process for e.g. Document Driven Approach (where various documents are the driving factor for development process), Model Driven Approach a.k.a. MDA (where models typically UML models are the driving factor), Test Driven Approach (where test cases are the driving factor), Functional Points Driven Approach a.k.a. FPDA (where functional points are the driving factor) etc.

    In this article I presented a new driving approach and called it Unit Test Driven Approach (UTDA). Although this may not be a known or standard term in software industry right now, I evolved and adopted the same in one of the projects recently and found extremely helpful in specific situations. In this article I tried to cover introduction and advantages of this approach along with specific scenarios where it could be proved exceedingly helpful.

  2. Suitable Scenarios
    Unlike other articles, where the approach is defined and explained before depicting the amiable situations where it is suitable to use, I feel that it would be helpful to take the reverse route. Listing scenarios where UTDA is most suitable; will not only help in understanding the uniqueness of this approach but also avoid ambiguity involved in the some of the assumptions in the definition of this approach.

    The UTDA suits best in the scenarios where part or whole UI/Code is ready. Although the section below explains elaborately the reason for this requirement, it is helpful to note here that in UTDA, the test plan is built by developers looking at the actual UI and code. In the view of this requirement few of the scenarios where UTDA suits best are listed below.

    1. Technology Migration Projects: UTDA may suits best in projects involving migration from one technology (typically legacy) to another technology where existing product is used as benchmark for requirements and functionalities of the new product.

    2. Language Migration Project: This involves projects where the exiting product supporting a specific human language needs to port to support another specific language.

    3. Localization Projects: Projects where a product is enhanced to support I18N also best suits for UTDA.

  3. Unit Test Driven Approach
    In Unit Test Driven Approach (UTDA), the unit test plan composed by developer team (with optional help from testing/QA and business team) is the driving factor for development process. It is important to note that the term UTDA includes the word ‘Unit’ which indicates that the development process is and should be divided into logical units. Although the definition of a ‘Unit’ is not arduous and each environment may define it in its own way, it may range from a simple actionable item on UI to a complete module. Thus the 1st task in UTDA is to define the unit and then prepare test plan for it.

    The UTDA can further divide into 2 sub parts:
    1. Unit Test Driven Approach – UI based
      In this approach the unit test plan is prepared using the UI. The test planner should use the UI to find out all possible test cases. Incases where UI is not ready, the HTML wire frame, UI documents etc can also be used to accomplish this task.

    2. Unit Test Driven Approach – Code based
      In this approach, the test planner explores the code and then prepares test plan accordingly. This includes understanding the code and captures all scenarios and exceptional conditions.

    Combining the above 2 approaches results in a comprehensive Unit Test Plan, which then used as the driving factors for development activities.
    Once the unit test plan is ready, development team starts implementing the same followed by execution of the test plan as the ceasing step. In UTDA it is also recommend having peer or expert review and execution of unit test plan.

    To sum up the above paragraphs, the important steps involved in UTDA are listed below:
    • Preparation of unit test cases based on UI
    • Preparation of unit test cases based on code
    • Merging of unit test cases to prepare unit test plan with optional verification of the same
    • Implementation/development process
    • Execution of unit test plan
    • Optional expert (or peer) unit test execution
    • Code release to Testing/QA team

  4. How UTDA Different From Test Driven Approach ?
    It is important to note that UTDA is not same as Test Driven Approach (TDA) except the fact that both use test cases as driving factor. Incase of TDA the test cases are typically written by Testing/QA team and delivered to development team. Also in most of the cases these test cases are written based on SRS or other documents rather than actual UI or code.

  5. Advantages of UTDA
    UTDA is especially suitable where part/whole code base or UI is ready for reference and the further development is based on the same. Let’s cover some of the advantages of UTDA:
    • Scenarios where part or whole of the code/UI is available UTDA can be proved extremely helpful as it involve exploring UI and code while preparing Unit Test Plan.
    • UTDA is by definition completely compatible with Agile Methodology.
    • Unit Test Plan composed by development team can be proved very helpful and useful for Testing/QA team and results in saving lot of time especially incase of black box testing.

  6. Conclusion
    Unit Test Driven Approach (UTDA) is a very simple but efficient approach specially incases where some code/UI is ready for reference to development process.

Sunday, January 27, 2008

Competencies Based Interviews

Introduction: The recruitment process has always been the most critical aspect for the growth of any engineering or non-engineering industry. A good and efficient resource can help organization to set and achieve high growth whereas the vice-versa is also not false. With augmenting demand of deserving candidates in companies, the interview process has also undergone lots of revisions and changes.

In this article I tried to present few notable points regarding competencies based interviews along with merits of the same over traditional interviewing approach.

What is ‘Competencies Based Interview’?

Competency can be defined as a personal characteristic which is displayed by outstanding performers in a role in a given business environment and which is demonstrated through specific observable behaviors. In other words competency is the way one conduct/demonstrate his/her skills in the given environment.

In competencies based interviews, the interviewer tries to evolve, understand and judge the competencies of the interviewees in different areas including behavioral and technical fronts.

How Competencies Based Interviews are different from Traditional Interviewing approach?

Competencies based interviews tends to evolve the technical and non-technical skills of the candidate based on his/her knowledge, behavior and demonstration of the same while traditional interviews tends to evolve the technical and non-technical skills using results as the base line.

Traditional interviewing approaches were more based on ‘What’ kind of questions rather than ‘How’ and ‘Why’ kind of questions and were strongly supported by ‘Theoretical and Hypothetical questions’. For e.g. ‘What was your role in previous organization?’ but not followed by ‘How you managed that role, how you handle various challenges etc.

Few more drawbacks associated with traditional interviewing approaches were:

  1. Lack of clear job profile and competencies required for the same.
  2. Lack of interview preparation and structure.
  3. Poor follow-up questions.
  4. Involvement of various biasing aspects.
Moving forward, in this article, I will try to explain these points in depth and describe how competencies based interviewing approach handles these issues.

What is the structure of a Competency Based Interview?

The structure of a typical Competency Based Interview is:
    1. Introduction by Interviewer
      Introduction of interviewer is as important as that of interviewee. Although the interviewee’s information is present in the resume or CV but the interviewer’s information in nowhere mentioned in the interview in most of the cases. A good introduction of interviewer makes the environment healthy and comfortable for both. This section can be optionally accompanied by brief introduction of organization as well.
    2. Rapport building questions
      Rapport building questions helps in building confidence of the interviewee and making environment comfortable.
    3. Explanation of Job profile and expectations
      A brief explanation of job profile and expectations in the interview helps both interviewer and interviewing in focusing on the important and relevant information.
    4. Behavioral Competencies based questions
      These questions help in judging the interviewee on the behavioral front. Please read the explanation below for detail on behavioral competency based interview.
    5. Technical Competencies based questions
      These questions indicate the technical strength of the candidate in relevant area.
    6. Questions from interviewee accompanied by optional feedback session
      Before ending the interview, the interviewee should be given an opportunity to ask any relevant question or clear any doubt. This section can be optionally accompanied by brief feedback session by interviewer.
    7. Interview close up
      It’s important to close up the interview with a positive attitude maintaining self esteem of the interviewee and expressing gratitude for taking interest in the organization.
    What are ‘Rapport Building Questions’ and why should we involve them in interviews?

    Rapport building questions includes questions not directly related with the job profile but are used to begin the communication.

    Few examples of rapport building questions could be:
    1. How are you today?’
    2. Do you face any problem in finding our office premise?
    3. How is whether condition there (especially in telephonic interviews)?
    4. Question/discussion related with any specific place, event or item of their native place for e.g. so you belong to Jaipur, I heard that it is called ‘Pink City’, do you know why?

    There are various advantages of these questions including:

    1. Help in making the environment comfortable for both interviewer and interviewee and boost up the confidence of the interviewee.
    2. Help in making sure that both are audible to each other especially incase of telephonic interviews.
    3. Demonstrate the candidate that this is a god place to work.

    What is Behavioral Competency Based Interview?

    Behavioral Competency Based Interview a.k.a. Behavioral Event Interview (BEI) includes questions related with the behavior or conduct of the candidate in his/her past job/organization or even personal life (useful incase of inexperienced candidate). The background assumption behind BEI is that the past behavior of a person best predicts the future conduct. Thus BEI involves question related with past behavior of the candidate to understand and predict his/her conduct in future and suffixed by follow-up questions to gather more useful data. Few examples of BEI questions:

    1. Tell me about an instance where you dealt with a client who changes requirements very often and these changes resulted into lots of re-work and slippages? The follow up questions could be ‘How you handle the situation, how you manage your team in that scenario, how you convince your manager at your end, how you faced the challenges and what were learning from that instance, did you get chance to apply that learning in other projects etc.
    2. Can you tell me an example where you have a deadline nearby but unfortunately 1 or 2 key resources of your team went on emergency leave or left the organization? Follow up question could be ‘How you communicated with client, how you managed your team, what extra efforts you put into the project, what were your learning from that instance etc.

    In traditional interviews the theoretical questions were preferred over behavioral questions for e.g. the theoretical version of the 1st example above could be: Tell me if you need to deal with a client who changes requirements very often which may result in lots of re-work and slippages, how will you handle the situation? The drawback of theoretical questions is that the candidate can use his/her good communication skills to answer such questions wisely but not necessarily execute the same. Thus it resulted in more useless data.

    In traditional interview question the end result is more important but in behavioral interview the approach, behavior, conduct, learning, execution and other aspects are also important along with results.

    One more important point to note here is the difference between behavioral and non-behavioral answers. For e.g. the answer ‘I proved as a great manager in my last project. The project was delivered on time with excellent quality. Our client also appreciated the same.’ is an example of non-behavioral action. Notice that in this answer, no useful data could be collected because it doesn’t indicate how he/she managed the team, how he/she faced critical and complicated situations, what issues/problems he/she faced and resolved etc. Thus it is important for an interviewer to recognize the non-behavioral answers and use follow-up questions to get more information.

    It should also be noted that in behavioral interviews it’s important that answers should indicate a complete behavior consisting of context, action and outcome. For e.g. the answer ‘In one of my previous projects, one of the resources left the organization just before project deadline and I took efforts to manage that’ misses the action (to some extent) and outcome. The above answer doesn’t indicate the actual action and what happened finally and learning from this instance.

    What is the importance of follow-up questions in BEI?

    To illustrate the important of follow-up questions let me quote snippet from a recent interview…
    Interviewer: Can you give me a recent example where you own the complete module and delivered it on time in constraint of deadlines?
    Interviewee: In the last project, I completely owned one of the modules in the application and since the deadline was nearby we delivered it without testing cycle and later recognized that there were no bugs in the module.

    At this point it seems to be a great work. But let’s see the follow-up question:

    Interviewer: Can you explain more about that module?
    Interviewee: The module was ‘help’ module which opens various manuals of the application on user’s request.
    Interviewer: How much code you wrote for the same?
    Interviewee: It was 1 JSP page.
    Interviewer: Did you also write or manage the manuals?
    Interviewee: No those were written by Technical Writing Team.

    The above communication indicates the importance of follow-up questions to get more realistic data.

    Remember that the ultimate goal of the interview is to get the most useful data regarding the interviewee to help making effective selection and in this regard follow-up questions can be proved critical to get more and more information.

    What are important things to notice while asking technical competency based question?

    Technical competency of a candidate is the demonstration of his/her technical skills in the given business environment. This section is very critical as it judge the interviewee on the most critical and relevant part i.e. technical caliber. Questions in this section should be cleverly designed to not only gauge his/her technical strength but also instances and way he/she demonstrated the same in previous job. Few important guidelines for technical competency questions are:

    1. Avoid questions which requires more cramming but ask questions which requires more logic.
    2. Use more analytical and general questions. Don’t use uncommon terminologies.
    3. Try to cover more depth rather than width. Ask simple concepts and explore in depth rather than covering everything.
    4. Be specific and focused in the technical requirements.
    5. It’s is very important that you rephrase the important questions if the same is not clear to interviewee.

    What are major biasing factors during interview?

    Below are few examples of biasing factors which an interviewer should neglect to make effective results:

    1. Pressure to fill positions: Most of the time interviewer says that the position was open for a log time and ultimately I decided to compromise on that. In long term this may result in serious impact on the project and organization growth.
    2. Contrast effect: This is again a trivial factor with most of the interviewers. The goodness or poor performance of one candidate affects our attitude towards other candidates. This is true especially incases of weekend drives and walk-ins.
    3. Regional and religious biasing: ‘Some one belonging to the same part of country as you’ or ‘Some one belong to the non-reputed state of the country’ or ‘Some one belongs to majority/minority community’ etc are most common factors affecting the interviews.
    4. First Impression: Many interviewers got biased with the 1st impression of the candidate or the gesture and dressing code of the candidate.
    5. Halo and Horn effect: Halo effect means impressing with one quality to such extent that you neglect all other drawbacks while horn effect means you neglect all god qualities because of one drawback. An interviewer should always try to come out of halo and horn effect.

    At the last, I just wanted to list down some tips for effective interviews:

    1. Focused: Interview is also knows as ‘Mining the skills’ and as in mining it’s very important to follow a vertical path to avoid danger of loosing the track, similarly in interviews it’s very important not to loose the focus and deviate from main track.
    2. Avoidable Question Types: It is recommended that in interviews the ‘Yes/No’ type of question should be avoided as they don’t result in any valuable data. Also leading, confusing and complex questions should be avoided. (Lending question includes those the answer of which lies in the question itself for e.g. ‘I think you can handle a big team?’)
    3. Non-Question Questions: Nowadays non-question questions are proving very effect in interviews. Thus instead of asking ‘What are your best skills?’ ask ‘Your resume seems to be impressive but to better know you, can u help me by telling your best skills?’
    4. Simple and Straightforward: It is highly advisable to keep the questions simple and straightforward so as to get better results and useful data. Use your effective communication skills to explain the questions if required. Avoid using uncommon terms and misleading phrases.
    5. Maintain Candidate’s Self Esteem: It’s very important that after interview, the candidate shouldn’t feel guilty or insulted. Being on the decision-making-chair, it’s the responsibility of the interviewer to maintain the self esteem of the candidate which not only resulted in healthy environment but also sends an impressive message in the community regarding your organization.

    Thursday, January 10, 2008

    Is Java an Object Oriented Programming Language?

    In this era of computer science, where computers are presumed to provide solution to every real world problems, it is highly essential to adopt Object Oriented Programming Model. To achieve this, it is quite mandatory that the underlying programming language provides inbuilt support for this programming paradigm.

    Java, being considered as one of the most successful and versatile computer programming language, also fits in the above requirement. Now the question comes in every programmer’s mind: Is java an Object Oriented Programming (OOP) Language?

    In this article I tried to answer this critical question taking help from theoretical concepts.

    As per the definition of Object Oriented Programming, a language can be categorized as PURE OOP based on following criteria:
    1. The language must have inbuilt support for encapsulation and abstraction.
    2. The language must have inbuilt support for Inheritance.
    3. The language must have inbuilt support for Polymorphism.
    4. All system defined types must be objects.
    5. All user defined types must be object.
    6. The only way of communication between objects is through the methods exposed on the same.

    Criteria 1 to 3 are self explanatory and don’t require further clarification. So I am escaping those. Now consider criteria 4.

    Criteria 4 states that all predefined types in the systems must be objects only. This means there can’t be anything other than objects defined by system. This is the first requirement where Java fails to fulfill the criteria to be categorized as pure Object Oriented Programming. Java has primitive types, which are not objects and thus violates this rule.

    Criteria 5 suggests that all user defined types must also be objects only. This means users can’t define or create anything other than objects. This restriction is not applicable in using system defined types. Java successfully follows this rule where user can’t create or define anything other than objects.

    Criteria 6 suggest that whenever objects communicate with each other, they communicate using the methods exposed on other objects. And this should be the only way of communication. Java violets this rule by using various operators. Consider the ‘+’ operator on String literals which can be used to add 2 or more string objects. By using this operator java violets the rule of object communication using methods. This holds true for other operators on primitive types as well.

    Summing up the above points, java fulfils the criteria 1,2,3,5 but fails in 4 and 6. Failing of these 2 criteria deprived java from being categorized as PURE Object Oriented Programming Language. But still the programming community categorizes Java as OOP (although not Pure). In theory such languages are called ‘Hybrid OOP’ languages.

    Monday, November 26, 2007

    Creating Threads: Extend Thread Class OR Implement Runnable Interface


    1 Introduction
    In this article I tried to answer the most common question regarding the creation of threads in Java: whether to implement Runnable interface or extend Thread class? While answering this question I also tried to cover the basic concepts involved in similar scenarios.

    2 Whether to implement ‘Runnable’ interface or extend ‘Thread’ class?
    In java sometimes we enjoy the liberty of implementing similar code in multiple ways. Although most of the times from a helicopter view we couldn’t figure out the subtle issues involved in each way unless we go into depth. The same holds true in this scenario as well.

    In regard to the above question, I answer it in 3 parts.

    1. Technical Constraint:
    Although java supports multiple type inheritance, it doesn’t support multiple class inheritance. In other words, a class or interface can inherit from multiple inheritances, but a class can only inherit from one super class. Under this technical constraint, if a class extends ‘Thread’ class, it can’t extend any other class. Thus we loose the liberty of inheritance in this case. In view of this constraint, implementing ‘Runnable’ interface remain the only choice incase the class already inherit another class.

    2. Semantic Difference:
    Inheritance, being ‘is-a’ relationship, provides semantic definition of the class and categorize it to the category of the super class. Moreover incase of type (interface) inheritance, class or interface also provided with additional semantic ability. For e.g. when a class implements a ‘Serializable’ interface, it belongs to ‘Serializable’ category where it gets the ability to be serialized.

    Thus in the above scenario, if your code semantically suitable to be categorized as a ‘runnable’ code which can run using a thread, it would be logical to implement the ‘Runnable’ interface. On the other hand, if your code is semantically like a thread in itself and can run itself as a thread, it would be semantically good to extend the ‘Thread’ class.

    3. Implementation Difference:
    The above two points are easy to understand and implement but at the last I would like to touch the most subtle issue involved in the above scenario.
    Note that when we implement the ‘Runnable’ interface, our class is acting as a factory for creating threads. Thus all threads execute the run (and hence all non-static methods) of the same instance of the class. Thus if the run method of the class implementing ‘Runnable’ interface executes any synchronized method or block, all generated threads need to acquire lock of the same instance of the class. But incase of extending from the thread class, every new thread is a new instance of the class. Thus if run method internally executes any synchronized method or block, each thread needs to acquire lock on its own instance instead of any single instance. The explanation in this paragraph is depicted below in the figure.




    To further explain this, let’s consider the code below:

    public class RunnableClass implements Runnable {

    public void run() {
    m1();
    }

    public synchronized void m1() {
    System.out.println("Lock acquired by [" + Thread.currentThread().getName() +"] Thread on instace: " + this);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    public void m() {
    Thread t1 = new Thread(this, "T1");
    Thread t2 = new Thread(this, "T2");
    Thread t3 = new Thread(this, "T3");
    Thread t4 = new Thread(this, "T4");
    Thread t5 = new Thread(this, "T5");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    t5.start();
    }

    public static void main(String[] args) {
    new RunnableClass().m();
    }
    }


    The output of this program would be similar to this:

    Lock acquired by [T1] Thread on instace: com.test.general.RunnableClass@9304b1
    Lock acquired by [T5] Thread on instace: com.test.general.RunnableClass@9304b1
    Lock acquired by [T4] Thread on instace: com.test.general.RunnableClass@9304b1
    Lock acquired by [T2] Thread on instace: com.test.general.RunnableClass@9304b1
    Lock acquired by [T3] Thread on instace: com.test.general.RunnableClass@9304b1

    Note that the id of the object on which lock is to be acquired by all threads is same. This evident that all threads will compete for the same lock hence if the run method internally calls synchronized method or block, the performance could be a major concern here.

    Now look at the code below where ‘ThreadClass’ extends ‘Thread’ class.

    public class ThreadClass extends Thread {

    public ThreadClass(String name) {
    super(name);
    }

    public void run() {
    m1();
    }

    public synchronized void m1() {
    System.out.println("Lock acquired by [" + Thread.currentThread().getName() +"] Thread on instace: " + this);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    public static void main(String[] args) {
    new ThreadClass("T1").start();
    new ThreadClass("T2").start();
    new ThreadClass("T3").start();
    new ThreadClass("T4").start();
    new ThreadClass("T5").start();
    }

    public String toString() {

    return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    }

    The output of this program would be similar to this:

    Lock acquired by [T1] Thread on instace: com.test.general.ThreadClass@9304b1
    Lock acquired by [T3] Thread on instace: com.test.general.ThreadClass@a90653
    Lock acquired by [T5] Thread on instace: com.test.general.ThreadClass@c17164
    Lock acquired by [T4] Thread on instace: com.test.general.ThreadClass@1fb8ee3
    Lock acquired by [T2] Thread on instace: com.test.general.ThreadClass@61de33

    Note that the id of the object on which threads acquired lock is different. This means each thread needs to acquire lock on its own instance and hence if the run method internally calls synchronized method or block, threads need not to compete with each other to execute the same.

    The above point suggests that incase the thread needs to execute some synchronized method or block, ‘extending Thread class’ could be a better solution.

    3 Conclusion
    Threads in java can be created in 2 ways. One can select an appropriate way depending on the hierarchy of the class, semantic definition of the class and execution of non-static synchronized code.

    Friday, November 23, 2007

    Singleton Pattern: The Unheeded Aspect

    1 Introduction:
    Singleton pattern is probably one of the most common design patterns being used in software development processes. It is also one of the simplest patterns from implementation and use perspective.

    In this article I tried to light up some of the subtle facts regarding singleton pattern especially in java context. The aim of this document is to explore singleton pattern in depth especially the unheeded facts involved in it.


    2 Singleton Pattern

    2.1 A Quick Introduction:
    Before putting forward some of the untouched features of Singleton pattern, let’s see a brief introduction of singleton pattern. Note that, although the definition quoted below is the most common definition of single pattern, the same is updated / changed below in this article when we explored singleton pattern in depth.

    Definition: Singleton pattern assured that there will always be a single (one) instance of the class present in the run time environment.

    Although, the above definition is the simplest to define singleton pattern, it indeed is neither complete nor correct. Before we explore the incompleteness and incorrectness of this definition, let’s see a simple way to implement singleton pattern (as per above definition) in java:

    public class Singleton {

    //The single instance of the class.
    private static Singleton instance;

    //Private constructor to avoid creation of multiple instances //from outside
    private Singleton(){
    }

    //Static method returning the single instance of the class.
    public static Singleton getInstance() {
    if (instance == null) {
    instance = new Singleton();
    }
    return instance;
    }

    }

    Code Listing 1

    The above code is as simple as the above definition. It explored a static method to get the single instance of the class. Also note that the constructor is private hence the class can’t be instantiated from outside. This will ensure that there will always be one instance of this class.

    2.2 It’s Not Singleton Instance Pattern:
    So the first incorrect word in the above definition is ‘single instance’. The pattern doesn’t restrict itself to the single instance, but to a single object (class or instance).

    Look at the code below:

    public final class SingletonClass {

    //private constructor
    private SingletonClass() {
    }

    //Static method
    public static void method1(){
    }

    //All remaining methods are static
    }

    Code Listing 2

    In the above code the class is final with optional private constructor and all methods as static. This will ensure that there will always be one class object corresponding to this class with no instance. This is another flavor of singleton pattern.

    2.3 Java Doesn’t Support True Singleton Patterns:
    Yes, this is a fact: java doesn’t support singleton pattern to its true flavor. So, the next incorrect word in the above definition is ‘run time environment’. Let’s discuss the issues involved in true implementation of singleton pattern in java.

    1. Issues with Class loaders:
    In java, a class loaded in JVM is recognized not only on the basis of its fully qualified name but also on the basis of the class loader responsible for loading it in the JVM. Thus if a singleton class is loaded with different class loader (the word class loader here refer to application/system class loaders or user defined class loaders extending application/system class loaders and also assuming that they are not in the same hierarchy), we will have that many instances (objects) of the class in JVM. In other words, while loading a class the JVM checks whether the same class is loaded by any class loader in the hierarchy or not. The class will be loaded only if none of the class loaders (in the same hierarchy) loaded the class. But incase the class loader is changed the same class will be reloaded and instantiated again provided the new class loader is not in the same hierarchy. Hence you may have multiple instances of a singleton class in the JVM using multiple class loaders.

    Although this is a fact and has no solution, still it is an unheeded fact simply because of 2 reasons:

    1. Rarely we write our own class loader and use it to load the classes.

    2. Even in cases where a programmer writes his/her own class loader, most of the time he/she follows the same hierarchy.

    Still it becomes a troubling issue many times for e.g. incase of web servers which uses new class loader for each Servlet even in the same web application.

    2. Issues with Serialization:
    Imagine a scenario where singleton class implements serializable interface. In such cases one can serialize and de-serialize the singleton instance of the class to get another instance in the same JVM. Although this is a rare situation and with proper implementation it can always be avoided, still it questions the implementation of true singleton pattern in java.

    3. Issues with Threading:
    In the code listing 1 above, imagine that multiple threads access the singleton class at the same time to get the instance for the first time. It might happen that these threads executes the line ‘if (instance == null)’ of getInstance() method at the same. This may result in creation of multiple instances at the same time. Although this is a result of wrong implementation of the entry method i.e. getInstance() but still depict the threading issues in java related with singleton pattern implementation. The above mentioned problem can be solved in 2 ways.
    1. Initialize the variable ‘instance’ at the time of declaration. But this will be against the optimized rule of lazy loading where the instance of the class is not creating unless it is required.

    2. The 2nd and most effective solution is use of either ‘synchronized’ block or method.

    2.4 Few More Subtle Points Regarding Singleton pattern:
    1. Issues with browser JVM incase of applets:
    Although the issues vary from browser to browser, I am picking the most common MS Internet explorer and 2 most commonly faced issues related with singleton pattern incase of applets:

    1. If your page contains applet(s) which uses singleton patterns and you open a new window from this page (for e.g. using window.open() in java script), the same JVM will be shared between the parent and child browsers. In other words, the child browser will share the JVM of its parent and hence if the child browser too contains applet(s) and using the singleton class, note that the parent and child browser’s applet will use the same instance. Sometime this is a desirable condition but many a times it is categorized as a problem.

    2. On the other side of the coin there is an issue related with different frames on the same page. If your page is divided into frames and each frame has applet(s) using singleton pattern, then each frame will have its own JVM and hence the singleton instance will be per frame instead of per page.

    2. Issues with distributed application:
    In distributed environment, the application is deployed in fractions on different JVM and hence the singleton instances are not same throughout the code. Hence it is highly advisable to use singleton pattern in distributed environment in such a way that the same is restricted to one runtime environment. In other words the use of the singleton class should be logically categorized based on the code deployed on a single JVM instead of using the same singleton class across different runtime environment.

    3. Issues with clustered environment:
    Clustered environment, where multiple servers are used to serve the client requests, also brings lots of issues related with singleton classes. This becomes more prominent when the ‘Sticky Session’ approach is used where any server in the cluster can serve any request irrespective of the condition whether it or any other server has served the last request from the same client. In ‘Sticky Session’ approach all live sessions are replicated to all servers in the cluster and hence singleton instance creates problem when the session is replicated between servers. Thus one must be very cautious while using singleton pattern in clustered environment.

    3 Conclusion:
    Although one of the most simple and commonly used design pattern, singleton pattern has many subtle issued associated with it especially in java platform. One must take a judicious decision while using pattern and should considered all possible consequences before implementing singleton pattern in the application.

    Monday, November 5, 2007

    Gr8 Tips for Design

    Design adds value faster than it adds cost --Joel Spolsky

    Design has always been the most critical and prominent phase of a software development process. A good design not only ensures smooth implementation but also provides enough flexibility to accommodate future changes.

    The aim of this article is to provide some useful tips which can help confirming a good design. This article shouldn’t be read as a tutorial to master the design or deeply understand every aspects of design, instead it should be used as a reference to confirm the wellness of your design. The article is structured with tips for good design along with few questions in each section which confirms whether the design follows the underlying principles or not. This unique way makes it easy to use this document as a final check list to affirm the quality of the design.

    1. Modularization
    One of the first goals towards a good design is to keep the modules of the application as logically divided units, each corresponding to a specific business need. The system should be designed in the way that the logical separation between modules is maintained in conjunction with the re-usability of the common logic and code. In large applications modularization become more prominent and unavoidable.

    To confirm whether your design is modular or not, answer yourself the following questions:

    1. With this design, can we distribute the application, in a workable format, with the addition or removal of one or more modules of the application (obviously keeping logical dependency in mind)?
    2. Is the successful execution or failure of one module doesn't impact the execution of other modules?
    3. Can we add/remove/change a module in the system without majorly affecting other modules?

    If answers to these questions are ‘yes’ or 'nearly yes', your design is modular in nature.

    2. Reusability
    Reusability of the design, code and logic is one of the salient measures of a good design. The increased reusability of the code assures centralization of logic and hence lesser efforts towards changes.

    To confirm whether your design has reusability feature, you can ask following question to yourself:

    1. Have we used the same design to accomplish similar business functionalities?
    2. Have we designed so as to reuse the same code for the similar business or application logic? OR Is our logic is centric and reused at multiple places wherever required for e.g. central logic for logging,/auditing error handling, localization and so on?
    3. Have we used Abstraction, Inheritance and factory pattern, wherever applicable, to ensure reusability ?

    If answers to these questions are ‘yes’ then you are definitely in the category of reusable design.

    3. Loose coupling
    Loose coupling, in broad way, indicates that the two components/tiers/layers, while communicating with each other, are not impacted with changes in other provided the communication protocol is not changed. Loose coupling can even be extended to the situations where the two components/layers/tiers lie in different technologies, languages or platforms. Interface based design in object oriented programming languages and Service Oriented Architecture are few examples where loose coupling is implemented to ensure these characteristics.

    To confirm whether your design is loosely coupled, ask following following questions:

    1. If we change the implementation of a particular component or tier (web, business, persistent), the other components or tiers in the system don't need any change?
    2. If we choose different technology or platform for one tier, it doesn't require any internal changes in other tiers (except the code responsible for establishing communication channel for e.g. service locator)?
    3. Have we used ‘interface based programming’, business delegate and service locator patterns to ensure the loose coupling in code?

    Positive answers to these questions indicate loose coupling of design.

    4. Changeability
    ‘Change’, as we all know, is an unavoidable and the most expected happening in software life cycle. The change could be in business requirements, underlying technology/API/tools, or even in design/architecture. Although being stated as the most expected thing to happen in software life cycle, designer has to take a judicious approach to provide flexibility for changes in design, so that neither it is too much flexible to anticipate huge changes nor it should be too arduous to accept any change in future. Many times, domain and business understanding of the product, discussion with product management team and thorough product understanding can help in taking this decision.

    To confirm whether the design is changeable, the designer can ask himself the following questions:

    1. Will it take least possible effort to accommodate a feasible change in business or technical requirements of the application?
    2. Have we kept the logic of (anticipated) changeable business functionality at a center location so that changes here resulted in least impact on rest of the code?
    3. Is our design loosely coupled with the frameworks, 3rd party API, containers, servers and other outer entities, so that changes in any of those don’t impact our design?

    If answers to these questions are ‘yes’, your design also has 'changeable' feature.

    5. Scalability and Plug-ability
    A good design provides scalability with ease. The term scalability, in general sense, indicates the capability of the system to perform well in the situations of high data volume or users or service requests. A good design should always be done keeping in mind the scalability aspect of the application. A slightly related feature is functional/technical extendibility, which indicates the capability to add new application functionality or a technical features with ease. An example of technical extendability could be a good I18N framework, which uses .properties file as resource bundle but provided with felxibility to extend code to consider XML or txt files as resource bundles in future.

    On the similar line, plug-ability allows adding new functionalities or features in the system on the lines of already existing features for e.g. a good web application could be designed in such a way that a new module could be added by adding a jar file and minimal configuration.

    To confirm whether the design is Scalable and Pluggable, the designer can ask himself following questions:

    1. Have I used polymorphism and other relevant practice to make sure that the use of functionality is not tightly couple with its implementation, so that I can provide room for scalability of the code?
    2. Have I provided sufficient API for the functionalities to be extended?
    3. Have I provided room in the design to incorporate other features as pluggable in the system?

    If answers to these questions are ‘yes’ then the designer can affirm that the design is scalable and pluggable.

    6. Robustness and Stability
    A robust and stable design ensures that the system won’t crash or fail in any condition whether it is favorable or disastrous. In other words, the system will handle all inputs gracefully whether in correct or incorrect format.

    To confirm whether the design is robust and stable or not, the designer can ask following questions himself:

    1. Have I handled all possible erroneous conditions in the system?
    2. Have I designed comprehensive test cases to make sure that the system is unit tested against all possible input information?

    If answers to these questions are ‘yes’ then the designer can affirm that the design is robust and stable.

    7. Configurability
    One of the biggest challenges in design is to make sure that the system will run equally good in heterogeneous environment by simply changing the configuration accordingly. Providing configurability in design means externalization of static and external information (may be in some xml file) so that the same can be changed without the need of any code change or even re-deployment in best cases. For an example, in an application requiring DB connectivity, the information like DB URL, driver class name, user/password etc can be externalized to some XML or text file so that it can be changed at runtime without the need to redeploying the application or any code change.

    To confirm whether the design is configurable or not, the designer can ask following questions himself:

    1. Have I externalize all static and external information in the system?
    2. Does any change in the external information like DB, JDK version, XML Parser/Transformer/Data Binder, log and audit file etc can be accommodate in the system without any code change?
    3. Is the mechanism for gathering external information like GUI or XML file, is capable enough of holding complete required information?

    If answers to these questions are ‘yes’ then the designer can affirm that the design is configurable.

    8. Testability
    The last but not the least is testability feature in the design. Unit testing has become one of the basic requirements for the success of the software. The design should provide room to accommodate testability in the same. As the word explains itself, testability feature makes the environment easy to plan, compose and execution of test cases to test all functionalities at unit level.

    To confirm whether the design is testable or not, the designer can ask following questions himself:

    1. Is the design provides easy environment to execute test cases to test all features in the application at unit level?
    2. Is the design compatible with the other unit testing framework like JUnit?

    If answers to these questions are ‘yes’ then the designer can affirm that the design is testable.

    An important point to note at the last is that, although categorized in separate sections, the above principals are closely related and dependent on each other. For e.g. the reusability not only avoids code duplication but also increases the changeability in the system. Similarly testability increases the robustness and stability of the design. Hence the principals are tightly coupled with each other and should be considered as complement of each other.

    In the last I would like to quote Sir Kevin Mullet’s great statement:

    The most powerful designs are always the result of a continuous process of simplification and refinement.