Monday, July 29

All about Anonymous Class


What is Anonymous class?

A class having no name is anonymous class. It falls in the family of nested classes in java. It is also called inner class

How is it different from a normal class?

1. It is not a member of enclosing class
2. Wherever it has to be used it is declared and instantiated there itself.
3. These classes can't extend any class and can't implement any interface.

What is the Use of Inner class?

You want to create a class on the fly. For example

to create comparators in a class where to want to sort objects list based on certain object properties

to create process objects such as Thread ,TimerTask,Runnable

These are very short lived and useful where we don't want classes or instances to live for long and wish to quickly use that and remove .

Sunday, July 28

Item 16 : Favor composition ovr inheritance


                 Favor composition over inheritance


How inheritance can be dangerous ?

 
Lets take an example

 public class X{

   public void do(){

    }

}

Public Class Y extends X{


   public void work(){

do();

}

}


1. As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature

public int work(){
}


Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be vary dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in suerclass all the time. So we need to avoid this strong and unnecessary coupling.


How does composition solves this issue?

Lets see by revising the same example

public class X{

public void do(){

}

}

Public Class Y{
X x=new X();

public void work(){

x.do();

}

}


Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class.
Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.


2. Second very good advantage of composition in that It provides method calling flexibility For example

class X implements R
{}
class Y implements R
{}

public class Test{

R r;

}


In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance

3. Another great advantage : Unit testing

public class X{

public void do(){

}

}

Public Class Y{
X x=new X();

public void work(){

x.do();

}

}


In above example If state of x instance is not known ,it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance As you were heavily dependent on superclass to get the state of instance and execute any method.

4. Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.

Lets take an example to understand this :


Class Deposit implements Banking{

 boolean deposit(){
}
}

class Credit implements Banking{
boolean credit(){
}
}
Public class Transaction {

}


In class Transaction , for complete transaction I have to invoke both deposit as well as credit method. I can't inherit both the classes to achieve this . But I can easily use composition to make it happen simply by doing this :

Public class Transaction {
Banking b;
public static void main(String a[])

{

  b=new Deposit();

   if(b.deposit()){

     b=new Credit();
     c.credit();

    }
 }
}




Good to know : 

        1. composition is easily achieved at runtime while inheritance provides its features at                      compile time 

        2. composition is also know as HAS-A relation and inheritance is also known as IS-A                     relation


So make it a habit of always preferring composition over inheritance for various above reasons.

Monday, July 22

What is covarient and invarient

Covarient simply means if x is subtype of Y then x[] will also be sub type of Y[]. Arrays are covarient
As string is subtype of Object So

String[] is subtype of Object[]


Invarient simply means irrespective of X being subtype of Y or not , List<X> will not be subType ofList<Y>.

generics are invarient

Although string is subtype of Object So

List<String> is not subtype of List<Object>

Out Of Memory issue in java -reason ,resolution ,monitoring - what and how?



1. Analyze heap dump. 

2. Use jVisualVM to figure out the biggest object and analyze if that size could be reduced.

3. Find out objects that are unnecessarily referenced for long time and that can be dereferenced to free some memory.

4. Increase the heap size If memory allocation is not sufficient 

5. Don't keep the variables referenced for long time If they are not required all the time . Better dynamically load them whenever they are needed instead of keeping them active in memory for a very long time.

6. Avoid static references If not required. These stay in the memory till class is finally unloaded Thus keep control of lot of memory space Which might not be required all the time. Program your program intelligently.

7. Tools like ZYourKit ,Jmemter,verbos GC log,JMX monitoring,Jconsole are very good to analyze the culprit responsible for out of memory occurrence .

8.Monitor the memory usage with load factor and time factor . If memory consumption is increasing due to increase in load ,it is not memory leakage problem Instead it is memory requirement by increased load . If memory consumption is increasing with time on same load It is surely memory leak and here you definitely need to resolve it otherwise later all memory will be consumed ans System will throw OutOfMemory error.

9. jmap in jdk 1.6 is excellent tool to analyze heap dump. Heap dump gives a very clear picture of objects and dependencies circulated in the memory 

10. Setting FISHEYE_OPTS to right value is important .

FISHEYE_OPTS="-Xms128m -Xmx1024m -XX:MaxPermSize=256m"  -- Java Heap space problem

FISHEYE_OPTS="-Xms128m -Xmx512m -XX:MaxPermSize=256m"   --- Perm Generation space issue

FISHEYE_OPTS="-Xms128m -Xmx1024m -XX:MaxPermSize=256m -Xss512k" -- new thread creation space issue

What is reordering in java ?

What is reordering in java ?

When you write a program you expect instructions will be executed in same order as written in the program . i.e. execution order will remain same as the order of instructions written in the program. 

But that is not the case 

Compiler is free to execute the instructions in order it desire . For Example :

Public class Order {

int a=8;
int b=6;

}

Here compiler might execute b=6 prior to executing a=8 . Thus the values for a and be might get flushed as b=6 and a=0 (default value) and a thread reading values at that point of time might read value as b=6 and a=0. 

Compiler is absolutely free to conspire and reorder the execution flow . 

Why does compiler do this?

Compiler do this to achieve overall optimization . Here a and b are independent of each other So compiler might think it hardly matters of a=8 executed first or b=6 executed first . But for overall optimization executing b-6 and delaying execution of a=8 provides better performance. 

Based on latest java memory model , compiler follow reordering more seriously for better performance and optimization . 

There are techniques available in Java to restrict this ordering. Synchronization is one of the finest example of applying that.