Refactoring legacy code to support Multithreading Enviroment




Refactoring Java code for Multithreading Environment


In my service life frequently I encounter a problem that a code is giving weird result in staging or production but when it runs from developer machine it shows a perfect result.

So, the clue is the weird result, try to run it many times and watch result pattern if it is varying then definitely it is due to threading. You can take Thread Dump for analysis but multiple tests give you a rough idea about Thread Problem.

Staging or production are  distributed environment where your resources are shared among multiple requests whereas developing machine there is only one thread involved. So it is run fine in developer machine.


It is very important to design your code for Multithreaded environment.

In this context, I can recall that once I have faced a problem , a module was designed for the stand-alone application. so developer implements the code without thinking of Multithreading as they know they will package the code into a jar then invoke from a command line which spawns a JVM and serves only one request.
So far so good but later a new change request comes that it should be hosted in Web, not as a standalone app. The Web means multiple requests so A New Problem was raised from nowhere. So there is no way but has to refactor the module to support Multithreading.

There are so many classes in a module some of them are pivot classes. Make it multithreaded capable is not an easy task. So we have to think a procedure by which we can do it in less time and minimally affecting the classes.

I want to share that experience with you people.

In that course, we think and try to understand where and How Multithread environment differs from a single thread environment.

Outcomes are.
1.       In Multithread environment problem occurs for the shareable resource which is not synchronized.
2.       If I filter the statement 1 , more specifically I can say shareable resource can create a problem If at least  one thread wants to update/write it states . then only we can encounter dirty data.
3.       If Multiple threads want to read from a resource, then we don’t need to alter them as It will not harm the state.
4.       What makes a shareable resource?
5.       If in a class, member variables are defined and have setter method then these classes are the potential candidate for causing the problem.
6.      If a class has methods and all variables are method level, then they inherently thread safe. We don’t bother them.
7.       If a class has Static variables they are very dangerous as the static variable bound to class and one copy shared by all Objects so, If a thread changes its value it reflects for all objects.
8.       In a project, I see every utility classes design as Singleton so we have to mark them candidate of Multithreading refactoring.
9.      In a project, it often happens a step is dependent on a previous stem or some derived value generated by some business logic. The developer is maintaining them as in Cache or in a Context and they are the potential candidate for Multithreading.
10.   Try to find any immutable class then they are thread safe so don’t need to refactor them.


Based on the Outcome we target our module and Identifies the classes need to be refactored. Believe me
This exercise will help you to find exact classes you need to refactor and you can discover they are the High-level classes like the manager or any factory classes Utility classes etc.

Next, the important question How to refactor them?

To Refactor they put your thinking Cap and try to pick the tools which will cause minimal change.

Tool 1:
Check you can refactor all member variable to method variable.
First check in that class how many methods use this member variable, then try to find out by searching your workspace from where these methods are called. If the number are small pass that variable as the method parameter and remove the member variable.

Suppose in EmployeeManager class Employee is member variable and in checkValidEmploye is method where you use Employee Object

Code snippet

Public class EmployeeManager
{
Employee emp;
Public void checkValidEmploye()
{
//some code using emp variable
}
}

Refactor the code

Code

Public class EmployeeManager
{
//Employee emp;// remove it
Public void checkValidEmploye(Employee  emp)
{
//some code using method emp variable
}
}

Call  employeeManager. checkValidEmploye(new Employee  ());



Tool2:

If there are so many member variables and you can’t make it local variables

Put the class in ThreadLocal

Code snippet
EmployeeManager mgr;
Public void validate()
{
                mgr. . checkValidEmploye();
               
}


Refactor Code snippet
private static ThreadLocal< EmployeeManager > THREAD_LOCAL_CACHE = new ThreadLocal< EmployeeManager >();;
Public void validate()
{

If(THREAD_LOCAL_CACHE.get() !=null)
{
       THREAD_LOCAL_CACHE.get(). . checkValidEmploye();
}
Else
{
THREAD_LOCAL_CACHE.set(new EmployeeManager() )
THREAD_LOCAL_CACHE.get(). . checkValidEmploye();
}             
               
}


By Thread Local we can ensure An EmployeeManager object exist for a thread. So EmployeeManager would be thread specific so no other thread can access one thread’s Employee manager. So mitigate the risk of dirty data


Tool3> Identify the classes which are singleton basically context,cache,utility classes are a singleton so make it thread safe. We can make it to Per thread Per singleton

Refactor singleton to normal class by a trick we can do that


Single to class look like

public class Utility
{
 private  static  Utility instance= new Utility();
private Utility()
{
}
Public static Utility  getInstance(){
return instance;
}


Refactor it like following to avoid change in calling classes


public class Utility
{

private static ThreadLocal< Utility > THREAD_LOCAL_CACHE = new ThreadLocal< Utility >();;

private Utility()
{
}
Public static Utility  getInstance(){
If(THREAD_LOCAL_CACHE.get()==null)
{
THREAD_LOCAL_CACHE.set(new Utility());
}
return THREAD_LOCAL_CACHE.get();
}

This will solve the multithreading problem as each request it will give a new Utility Object if it does not have as There is one object per thread we can put some variable to it and use it in future .


Please choose the option carefully. This is your experience and design decision which tool you are going to use to alter your code minimally.



















Free Java seminar at Bagbazar on 30-Jul-2016

Free Seminar on Java,  Absolutely free No registration fees . Based on First come
first serve basis
HOST: Shamik Mitra(IBM Tech-Lead)
Agenda
What is java
Why Java programing
OOPS principals
Class and Object
Basic syntax and keywords
Operators
Conditional statemants
Overloading and Overriding basiss
Collection frame works
Data structure
Thread Overview
Discussion



Prerequisite :  Basic knowledge on Computer
Basic sense on programing.

Bring Laptop will be benifical for student.
 
Feel free to contact 10.00 AM to 11 PM.
mob : 9830471739
email : mitrashamik@gmail.com

Pass user input from command line in java

There is a various way, you can pass parameter from a console . Using BufferdReader,InputStream but the easiest way to do it with Scanner class it took Inputstream(System.in) as parameter from we can get user given value

Let see an example



package com.example.userInput;

import java.util.Scanner;

public class UserInput {

    public void add(int i,int j)
    {
        int result = i+j;
        System.out.println("sum is " + result);
    }

    public void multiply(int i,int j)
    {
        int result = i*j;
        System.out.println("
Multiplication  is " + result);
   
    }

    public static void main(String[] args) {
   
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter Choice either a or m");
        System.out.println("Enter First Operend");
        int op1 = sc.nextInt();
        System.out.println("Enter Second Operend");
        int op2 = sc.nextInt();
        System.out.println("Enter Choice");
        String choice = sc.next();
   
   
        UserInput input = new UserInput();
        if("a".equalsIgnoreCase(choice))
        {
            input.add(op1, op2);
        }
        else if("m".equalsIgnoreCase(choice))
        {
            input.multiply(op1, op2);
       
        }
        else
        {
            System.out.println("Wrong choice Entered");
        }


Spring framework download and integration with eclipse step by step.

In this tutorial we will learn how we can download spring framework jars for eclipse and integrate the downloaded spring framework with eclipse . Then we create a basic Spring example to check our setup is successful or not.

Here are the steps to configure Spring core with eclipse IDE

1. Install JDK and eclipse
2. create a java project in eclipse called SpringTest
3. create a folder  lib under SpringTest\lib
4. Download commonLoggin1.2.jar from here http://commons.apache.org/proper/commons-logging/download_logging.cgi

5. extract it and put jars into lib folder earlier created.
6. Download spring from here
http://repo.spring.io/release/org/springframework/spring/4.1.6.RELEASE/
7. extract it and put all jars into the lib folder .
8. Right click on SpringTest ->properties->java build path
9. click on add external   jar and add all jars under lib folder
10.  Create a  folder called configFiles under SpringTest/ src folder.
11. create beans.xml file in configFiles

Add following lines

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.example.HelloWorld">
       <property name="greet" value="Hello World! Welcome to Spring"/>
   </bean>

</beans>


12 Create a package com.example under
SpringTest\src

13. create a java file HelloWorld.java under the package
com.example

14. Write following in HelloWorld


package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorld {
   
    private String greet;

    public String getGreet() {
        return greet;
    }

    public void setGreet(String greet) {
        this.greet = greet;
    }
   
   
    public static void main(String[] args) {
       
        ApplicationContext ctx = new ClassPathXmlApplicationContext("configFiles/beans.xml");
       
        HelloWorld bean =(HelloWorld) ctx.getBean("helloWorld");
        System.out.println(bean.getGreet());
       
       
    }
   
   

}
15. Run as java application output will be
Hello World! Welcome to Spring

multiple inheritance in java?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does Java support multiple inheritance?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does runtime polymorphism can be acheived by data memebrs?

No Overriding can not be performed on properties/data members it always call the reference class properties value

Let take an example

Public class Father
{

  public  int age=60;

}

Public class Child extends Father
{

  public  int age=30;

}


Now if Father f = new Child();
f.age print 60;

How does Map work in Java?

HashMap in Java works on hashing principle. The Map is a data structure which allows us to store object with a key and retrieve same by the same key. Hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method.

 When we call put method,internally  hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal LinkedList. If we dig down the structure we found HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object. When you want to retrieve the object, you call the get() method with  a key object. get() method again generate  key object hash code and eventually ended up with same  bucket location. and returns the value.

Few important things to remember , If you want to use your custom object as a Key of Map

1. It has to be immutable .unless  some one can  change the state.of the object
2. Must override hashcode. As good hashing algorithm, distribution of objects in bucket will be as good
.3. Must override equals method so in  the time of get operation  map  can fetch the key which is identically equal.

public final class CustomKey{
private final String name = "Shamik";
public final String setName(String name)
{
this.name=name;
}
public final String getName(String name){
return name;
}
public int hascode()
{
return name.hascode()*1245/7;
}
public boolean equals(Object obj)
{
if(obj instanceof CustomKey)
{
return this.name.equals(obj.name);
}
return false;
}
}

Here  name is not final so following scenario can occur
CustomKey refKey= new CustomKey();
Map<CustomKey ,String> map = new HashMap<CustomKey,String>();
map.put(refKey,"Shamik");
refKey.setName("Bubun");
map.get(refKey);

It will return null as when equals method invokes it return false. So immutability is must required.

what is servlet collaboration?

Servlet Collaboration means how one servlet can communicate with other. Sometimes servlets are to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods. To perform these operations, each servlet needs to know the other servlet with which it collaborates. Here are several ways to communicate with one another:


1. ServletContext :  In an application, there must be one Servlet context which is shared by all the servlets in this application. It works as a global map .each servlet put  necessary information , which needs to be shared
and other can get that info
  <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.example.ServletTest</servlet-class>
 </servlet>

 <context-param>
   <param-name>name</param-name>
   <param-value>Shamik Mitra</param-value>
 </context-param>




To get this
getServletContext().getInitParameter("email");

Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);

Java Singleton class :

public class Javacontext
{
   private static Javacontext ctx = new Javacontext();
private String name ="Shamik";
private Javacontext()
{
}
public static Javacontext getInstance()
{
return ctx;
}
public String getname()
{
return name;
}
}


Java Properties: Using java properties you can share information

import java.util.*;

public class PropDemo {

   public static void main(String args[]) {
      Properties prop= new Properties();
     Set<String> key;
   
      prop.put("name", "Shamik Mitra");
   

      // Show all states and capitals in hashtable.
      key= prop.keySet(); // get set-view of keys
      Iterator itr = key.iterator();
      while(itr.hasNext()) {
         str = (String) itr.next();
         System.out.println("The key is" +
            str + " name is " + prop.getProperty(str) + ".");
      }
   
   }
}

Can we Overload Main method in java.

Yes you can overload main method but public static void main(String[] args) is entry point in java. JVM always search for this method.
If it is not present in overloaded version ,when you try to run your code that gives run time exception no main method found.


From public static void main(String[] args), you can call other overloaded main function.

Keep in one thing in mind

If some one write

public static void main(String... args)//Varags

That is equivalent public static void main(String[] args) that will gives you compile time error.

Example :
package com.example.main;

public class OverLoadmain {
   
    public static void main(String[] args) {
       
        System.out.println("I am in main ");
       
    }
   
public static void main(int args) {
   
    System.out.println("I am in int");
       
    }


public static void main(String args) {
    System.out.println("I am in String");
}


/*public static void main(String... args) {
    System.out.println("I amn in varags ");
}*/

}