Monday 23 June 2014

Reflection

Reflection in java provides ability to inspect and modify the runtime behavior of applications. Reflection is one of the advance topic of core java. Using reflection we can inspect a class, interface, enums, get their structure, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values.

Fundamentally, the Reflection API consists of two components: objects that represent the various parts of a class file, and a means for extracting those objects in a safe and secure way. The latter is very important, as Java provides many security safeguards, and it would not make sense to provide a set of classes that invalidated those safeguards.

The first component of the Reflection API is the mechanism used to fetch information about a class. This mechanism is built into the class named Class. The special class Class is the universal type for the meta information that describes objects within the Java system. Class loaders in the Java system return objects of type Class. Up until now the three most interesting methods in this class were:

  • forName, which would load a class of a given name, using the current class loader
  • getName, which would return the name of the class as a String object,which was useful for identifying object references by their class name
  • newInstance, which would invoke the null constructor on the class (if it exists) and return you an object instance of that class of object

The Reflection API is symmetric, which means that if you are holding a Class object, you can ask about its internals, and if you have one of the internals, you can ask it which class declared it. Thus you can move back and forth from class to method to parameter to class to method, and so on. One interesting use of this technology is to find out most of the inter-dependencies between a given class and the rest of the system.

We should not use reflection in normal programming where we already have access to the classes and interfaces because of following drawbacks.

  • Poor Performance – Since reflection resolve the types dynamically, it involves processing like scanning the classpath to find the class to load, causing slow performance.
  • Security Restrictions – Reflection requires runtime permissions that might not be available for system running under security manager. This can cause you application to fail at runtime because of security manager.
  • Security Issues – Using reflection we can access part of code that we are not supposed to access, for example we can access private fields of a class and change it’s value. This can be a serious security threat and cause your application to behave abnormally.
  • Exposure of Internals - Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
  • High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t be found at compile time because the classes might not be available, making it less flexible and hard to maintain.

Example : Invoke method on unknown object
By using reflection, the code can use the object and find out if the object has a method called "print" and then call it.
package reflection;
import java.lang.reflect.Method;
 
public class Reflection {
 public static void main(String[] args){
  Foo f = new Foo();
 
  Method method;
  try {
   method = f.getClass().getMethod("print", new Class<?>[0]);
   method.invoke(f);
  } catch (Exception e) {
   e.printStackTrace();
  }   
 }
}
 
class Foo {
 public void print() {
  System.out.println("Hello World");
 }
}
Output :
Hello World

Read more information on Oracle website.

Friday 20 June 2014

What is Heap space in Java?

When a Java program started Java Virtual Machine gets some memory from Operating System. Java Virtual Machine or JVM uses this memory for all its need and part of this memory is call java heap memory. Heap in Java generally located at bottom of address space and move upwards. Whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java.


Some key points :-
  • Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
  • Before removing an object from memory Garbage collection thread invokes finalize() method of that object and gives an opportunity to perform any sort of cleanup required.
  • You as Java programmer can not force Garbage collection in Java. It will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
  • There are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
  • If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space.

Heap Generations for Garbage Collection in Java


Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.

New Generation is further divided into three parts known as Eden spaceSurvivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM.



Thursday 19 June 2014

What is a query cache in Hibernate?

The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries. Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.

Query query = session.createQuery("from Person as p where p.parent.id=? and p.firstName=?");
query.setInt(0, Integer.valueOf(1));
query.setString(1, "Joey");
query.setCacheable(true); //caches the query
List l = query.list();


You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.

<property name="hibernate.cache.use_query_cache">true</property>


Note that the query cache does not cache the state of the actual entities in the result set. It caches only identifier values and results of value type. So the query cache should always be used in conjunction with the second-level cache.

This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.


Why String is immutable in Java ?

This is an old yet still popular question. There are multiple reasons that String is designed to be immutable in Java. A good answer depends on good understanding of memory, synchronization, data structures, etc. In the following, I will summarize some answers.


1. Requirement of String Pool
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

The following code will create only one string object in the heap.
1.String string1 = "abcd";
2.String string2 = "abcd";
Here is how it looks:

2. Allow String to Cache its Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.

3. Security & Thread Safety.
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
Consider a scenario, in a banking application for money transfer - the beneficiary account number is defined in a string as "0123456789". If by mistake/intentionally this acc. number is changed, money will go to a wrong account.
Here is a code example:
1.boolean connect(string s){
2.if (!isSecure(s)) {
3.throw new SecurityException();
4.}
5.//here will cause problem, if s is changed before this by using other references.   
6.causeProblem(s);
7.}