Thursday, September 19

java composite design pattern , OO design pattern , composite tree design

              java composite design pattern , OO design pattern , composite tree design

-->


                                                           Composite Design Pattern

Composite design pattern is based on creating a tree structure in such a way that an individual leaf of the tree can be treated just like entire tree composition. Means all constituents of the tree consist of similar properties and can be represented with single interface.

 

For Example :

public interface Employee{

     public void addEmployee(Employee employee); 
     public void removeEmployee(Employee employee); 
     public Employee getEmployeeChild(int i); 
     public String getEmployeeName(); 
     public double getEmployeeSalary(); 
   
}




    public class Manager implements Employee{ 
     
     private String name; 
     private double salary; 
     
     public Manager(String name ,double salary){ 
      this.name = name; 
      this.salary = salary; 
     } 
      
     List employees = new ArrayList(); 
     public void add(Employee employee) { 
        employees.add(employee); 
     } 
     
     public Employee getChild(int i) { 
      return employees.get(i); 
     } 
     
     public String getName() { 
      return name; 
     } 
     
     public double getSalary() { 
      return salary; 
     } 
     
      public void remove(Employee employee) { 
      employees.remove(employee); 
     } 
     
    } 



    public class Developer implements Employee{ 
     
        private String name; 
        private double salary; 
     
        public Developer(String name,double salary){ 
            this.name = name; 
            this.salary = salary; 
        } 
        public void add(Employee employee) { 
            //this is leaf node so this method is not applicable to this class. 
        } 
     
        public Employee getChild(int i) { 
            //this is leaf node so this method is not applicable to this class. 
            return null; 
        } 
     
        public String getName() { 
            return name; 
        } 
     
        public double getSalary() { 
            return salary; 
        } 
     
      
        public void remove(Employee employee) { 
            //this is leaf node so this method is not applicable to this class. 
        } 
     
    } 



-->






public class CompositeDesignPatternMain { 
 
 public static void main(String[] args) { 
  Employee emp1=new Developer("John", 10000); 
  Employee emp2=new Developer("David", 15000); 
  Employee manager1=new Manager("Daniel",25000); 
  manager1.add(emp1); 
  manager1.add(emp2); 
  Employee emp3=new Developer("Michael", 20000); 
  Manager generalManager=new Manager("Mark", 50000); 
  generalManager.add(emp3); 
  generalManager.add(manager1); 
  generalManager.print(); 
 




Have a look at CompositeDesignPatternMain class carefully. Here using same interface Employee we are able to create a developer , manager and entire tree structure . In tree structure at top there is manager and below that that manager developers are added.

Similarly in other instance GeneralManager is at the top in the tree and manager and developer are added under it. Point to notice is that all tree structure and every individual leaf is being created using same interface . So the combination of Employee ,Developer,Manager is written is such a way  that reference Employee is sufficient to create a leaf of tree as well as entire structure . So here objects are composed in such a way that a single Employee reference can represent entire tree structure as well as single leaf of manager or developer or even any part of the tree .

Thus composition design pattern basically facilitate the concept of identifying commonality and designing various components around base structure in such a way that Base interface can suffice all leaf's requirement as well as can represent the entire tree structure.







-->


String concatenation trimming ,String immutability ,java String and memory management

String concatenation trimming ,String immutability ,java String and memory management





String s="hello";

This created an oject in memory

Object = "hello"    Reference =s

s+="World "

This creates a new object in memory

Object ="hellow world "  reference =s

Now in total , there are two objects in memory

 Object ="hellow world"  reference =s
Object = "hello"    Reference = none (no reference of "hello" object available)


s.trim();

What happens here?

A new object is created.

So now there are three objects memory

"hello"
"hello world "
"hello world"

and only "hello world " has a reference to it.






Strings are immutable objects. So once created can't be modified . On modification Java creates another String instance in memory. String pool maintains all string values at single place and If same oject is created multiple times java does not create multiple objects in memory but add reference to existing object. Thus an String can have multiple references in Java.










Wednesday, September 18

Apache Hadoop and Mumbai dabbawala .. Apache Hadoop is in practice for more than 100 years..

Apache Hadoop and Mumbai dabbawala .. Apache Hadoop is in practice for more than 100 years..
-->




  • Just like HDFS slices and distributes the chunk of data to individual nodes, each household submits the lunchbox to a Dabbawala.
  • All the lunchboxes are collected at the common place for tagging them and to put them into carriages with unique codes. This is the job of the Mapper!
  • Based on the code, carriages that need to go to the common destination are sorted and on-boarded to the respective trains. This is called Shuffle and Sort phase in MapReduce.
  • At each railway station, the Dabbawala picks up the carriage and delivers each box in that to respective customers. This is the Reduce phase.
Just like the way each node in the cluster does its job without the knowledge of other processes, each Dabbawala participates in the workflow just by focusing on his task. This an evidence of how a parallelized environment can scale better.



-->





-->

OO design principals and fundamentals , Java design principals





Rigidity

Tendency to change is very difficult. Any change will trigger many cascading change. Software modules are tightly coupled So very little flexibility.


Fragility

Tendency to break easily. Any change can trigger a lot of defects in lot of features. Creates unexpected problems . Hard to regress and write a proper test plan . Hard to cover all unit test cases. Bad design


Immobility

Movement is very hard. It requires lot of effort in moving a part of software from one section to other . Refactoring is not easy . A part of system that could be useful somewhere else could not be moved.







Viscosity

A system where doing right things is easy. Smallest change can trigger huge risk. When system becomes more dependent on hacks than actual design refinement Its viscosity is high . When System starts performing poorly and developers have no clue Where is the issue and they are forced to try and apply dangerous quick fixes and workarounds , Viscosity is high

Needless repetition

DRY design principal says Do Not repeat. Repetition makes a code difficult to manage and maintain . Software should be designed in a way that code repetition is avoided.


Opacity

A code having so particular pattern . Tough to understand . Very tough to read it .


SOLID design principals

SRS - single responsibility principal . A class or interface should take care of only one feature and should not mix many. For multiple features multiple classes/interface should be written. If a class has to be changed there should be only one reason of change. Class should never have multiple responsibilities

OPEN CLOSED Principal : A software should be open to extension but closed to modification. Behavior of class ,method ,interface should be extensible but should be available for internal modification. Abstraction is the way to apply this . Subclass of abstract class should be free to extend the features of abstract class But should be restricted to modify existing method or behavior.

LSP -Liskov substitution principal : A variable expected as argument in method should be replaceable by sub class of the argument type.

ISP - Interface segregation principal . Interfaces should be segregated intelligently and should not contain methods related to multiple features . Interface should be written in such a way that tit does not force any of it's client to implement a method forcefully .

DIP - dependency inversion principal . Basically push approach instead of Pull. Instead of a client ask for it's dependencies , those dependencies are plugged in in to the objects at the time of instantiation. Abstraction should not depend upon details instead details should depend upon abstraction


Http 1.0 versus http 1.1 protocol






Http 1.0 versus http 1.1

Http 1.0 is based on thread per request while http 1.1 is based on thread per connection.

What does that mean?

When a user send a request from browser Web Container allocate the request to a thread available in thread pool. Once response is returned ,that thread is released and is made available is pool again . This is http 1.0

In case of http 1.1 , This thread is not released but kept assigned to the user connection . So if user further send request , a new thread is not requested from threadpool instead same thread picks up that request and process that. This is http 1.1 . So here thread is not just one request scoped but stay alive for all connection duration.







Which is good ?

Won't it be a good idea to keep the thread allocated to a connection instead of just thread. In case of thread per request ,once one request is processed , thread is released So for next request http again need to negotiate and may need to wait if all threads are engaged and no ready thread is available in pool. waiting time can vary request to request based on availability of thread in pool. So overall response time for multiple requests would be very inconsistent and user experience can be very unpleasant.

Now let's talk about another scenario. There can a peak load time when thousands of user's areare accessing the website and to server those requests efficienlty it would require many threads . each connection need one thread in thread per connection scenario or once fixed number of threads in thread pool are exhausted next request will have to wait till a thread is available in the pool. So that would require too many system resources and will consume high memory

Moreover a thread will keep on waiting between two user requests. In that idle time thread could be used to do useful task for some other request.

So depending upon scenario you are dealing with there are pros and cons of both http 1.0 and http 1.1 


To remove all these bottlenecks a new approach is followed now a days. asynchronous call with thread per request model. 




 
In this approach
Thread keeps on doing useful task all the time . Anytime a processing consumes time, thread leaves that there and create asyncContext in application context. Once process is done with the current task it triggers an async even and container assign available thread to process further . Thus asynchronous approach is based on call back and a-sync events based techniques . Servlet 3.0 follows the same approach . Threads don't have to keep themselves in idle state while process is blocked for some resource like connection , I/O etc instead java SE 7.0 NIO is used to keep I/O calls non blocking.