Wednesday, 30 September 2015

Java Doesn't Support Pass By Reference

Pass By Value vs Pass By Reference

Pass By Value :  In pass by value, the copy of the value of the argument passed from calling method and the parameter of the called method receives that value. Since it just a copy so any changes to the parameter inside called method doesn't reflect to the argument of the calling method.

Pass By Reference : In this case, the address of the argument is passed instead of value and the parameter of the called method receives that address like thought pointer in C. 

But in Java there is no concept of Pointers. Since both the argument and parameter are references one can't hold the address of another rather holds the value of another reference. So every thing in Java is Pass By Value even though both are references.

Example of Proof : 



OutPut: 






Inside Memory :

Monday, 28 September 2015

Secret of Spring AOP.

How AOP works internally ? 

Here we will discuss on logging functionality as one of the AOP usages. Here I have implemented a POC using Java core API to demonstrate similar as Spring AOP functionality.

Prerequisite : Java Core Proxy API, Reflection API and Annotation API (java.lang.reflect, java.lang.annotation  packages)

Secret : Here also the main secrets are proxy object, MethodHandler, reflection and annotation. But the method handler class is main secret player of our discussion, which has the full controller on the proxy objects and when any method call happened on a proxy object it passes through the this handler. Inside the call back method of the handler, using reflection it introspects all the applied annotations and based on that it generates required log statements.


For more about Proxy object/Reflection API/MethodHandler, Please refer to my previous blog
http://secretsinjava.blogspot.in/2015/09/secret-of-spring-jpa-repository.html

Annotation API : Annotations are nothing but meta information about a program element like class, method, variables. Java API having so many built-in annotations but we can define our own custom annotation as well.

In this context using our custom annotations we will enable the logging functionality such that for every method call, based on the applied annotation the log statement will generate. Log statement can be before method call or after method call or on exception.


Source Code :
Annotations: Here We have created some annotations to annotate the method for which we want to generate the log


Worker.java
Here in WorkerController class, WorkerService field is assigned with proxy object, where as in Spring it will be auto wired by Spring Container.
AOPLoggingMethodHandler.java
 
Here in Main class also, WorkerController field is assigned with proxy object, where as in Spring it will be auto wired by Spring Container.
Output:



Thanks you for visiting the page. Please feel free to provide your precious suggestions and comments. 






Saturday, 26 September 2015

Secret of Spring JPA Repository

Here we will discuss on how Spring JPA Repository works. 
We will mainly focus on below couple of things : 
1.  How Spring provides Proxies for repositories 
2.  How Spring resolves the repository method name when there is no JPQL provided 

Before we start we need to know about some Java core API like Reflection and Proxy of (java.lang.reflect) package

Reflection API : Using this we can introspect any class and can create instance in run time and invoke any method of that instance. In a single line, we can have full control and information of that object.
Proxy API : Hep of this we can create proxy instance of any class and so that we can have full control of any method invocation. But here I am using javaassist library API for proxy creation since it has more flexibility than the core API

Secret : Here the secret is while creating proxy instance of any class the proxy API expects one MethodHandler. MethodHandler is nothing just an interface contains a call back method for which we have to provide the implementation of the method. 
The call back method supplies the parameters like
- the instance on which method invoked
- Method reference to the overridden method declared in the super class or interface.
- Method reference to the forwarder method for invoking the overridden method.  It is null if the overridden method is abstract or declared in the interface.
- arguments passed in the method invocation on the proxy instance
Object invoke(Object self, Method thisMethod, Method proceed,
              Object[] args) throws Throwable; 

Here if the method is abstract then the proceed method reference will be passed to the call back method as NULL. Then we can implement our logic to do what we want. Spring also does in the same way. It resolves the method name and do the required action. Based on the method name it fetches the entity(s) and returned back to the caller object of the repository. 
Source Code :
Egineer.java (Entity class)

 EngineerRepository.java

 Utils.java (To create list of static entities instead of taking fro DB and stores in PersistenceUnit class)

PersistenceUnit.java (Which holds list of static entities and help to fetch required entities on query)
EngineerRepoHandler.java (This is the secret class for handling all repository method invocation)
MyProxyFactory.java (Factory class returns the proxy of a class or an interface using javassist library)
SpringDataRepositoryPOC.java (Main class)

Output:

Please feel free to comment or suggest.



Secret of anonymous inner class

Why the method local variable access within inner class needs to be final or effectively final?

How Inner class access the variable of its enclosing class :
  • instance variable :  All inner class contains an internal reference of its enclosing outer class. Using this reference it access the instance variable of the outer class.
  • static/class variable : It is quite straight forward; it uses the class name directly to access the static variables
  • method local variable : This is the place where the inner class does not have any reference to the local variable since the local variables are created inside stack memory area in JVM. So the outer and inner class have an agreement that any method local variable accessed inside inner class are not going to be modified in future by declaring as final.If the local variable is not declared as final but not modified once it is assigned with the initial value, then that variable is known as effectively final. This time the inner class have the individual copy of local variables those are accessed inside inner class and which will not allow to to modify those variables at any cost.
Example Source Code : 
Compiled Inner class Code : 

Secret of Collections.sort()

How java.util.Collections.sort(List<T> list) works ?

Preface : 
  • All implementation class of List interface overrides toArray() method which returns an array of elements of that list. Except LinkedList all other list holds elements as a form of array internally. Only LinkedList holds in form of linked nodes (not in array form). 
  • List.toArray()
    • LinkedList iterates the linked nodes and store each node into a new array and returns the same
    • Other List implementation classes return a copy of the array that holds the element
  • Collections.sort():
    • sorts the array using Arrays.sort(Object[] a) which uses merge sort algorithm internally to sort the supplied array
    • then using ListIterator of the supplied list, it updates the elements from the sorted array

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    Object[] a = list.toArray(); // Gets array here
    Arrays.sort(a); // Sorting array here
    ListIterator<T> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);  // Updating list here
    }
}
Similarly it uses Arrays.sort(T[] a, Comparator<? super T> c) method when comparator is supplied