Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday 19 April 2015

Remote Connection Settings for MySQL

Configuring your MySQL to access it from outside i.e. from any machine across intranet / internet is one of the basic needs of the developer.

The following sequence of steps are needed to achieve this.

We have to do the following changes,
  1. Change bind address in MySQL configuration file my.cnf to 0.0.0.0  This allows mysql to bind to all interfaces. Previous value may be  127.0.0.1
  2. In mysql DB we have added new user  root@%  and granted all permissions to it.
Command for reference,
  • select host,user,password from mysql.user
  • create user 'root'@'%' identified by 'pass';
  • GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
  • GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;

We ideally will not require to do  anything in iptables (Linux Firewall)  but in some cases we would need to open 3306 port in the firewall settings. 

Saturday 18 April 2015

Getting JVM heap size, used memory, total memory using Java Runtime

Getting JVM heap size, used memory, total memory using Java Runtime.

Reading runtime java virtual memory usage is useful when the system/application is struggling in getting resources. System Memory is one of the main resource that an application developer has to consider while managing the application.

Java’s Runtime class provide lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class. Following is the  example of reading JVM Heap Size, Total Memory and used memory using Java Runtime api.

 public class MemoryUtilization {  
   public static void main(String [] args) {  
     int conversion = 1024*1024;       
     Runtime runtime = Runtime.getRuntime();       
     System.out.println("##### Heap utilization #####");       
     System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / conversion);  
     System.out.println("Free Memory:" + runtime.freeMemory() / conversion);  
     System.out.println("Total Memory:" + runtime.totalMemory() / conversion);       
     System.out.println("Max Memory:" + runtime.maxMemory() /conversion);  
   }  
 }  

Thursday 16 April 2015

How to create a read-only collection in java?

Collections is one of the most used feature in Java/J2EE applications . Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java.



 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ReadOnlyCollections {  
           public static void main(String[] args) {  
                List<String> myList = new ArrayList<>();  
                myList.add("1");  
                myList.add("2");  
                myList.add("3");  
                System.out.println(myList);  
                // Convert to unmodifiable .  
                myList = Collections.unmodifiableList(myList);  
                myList.add("4");  
                System.out.println(myList);  
           }  
 }  
 Output -   
 [1, 2, 3]  
 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollections.main(ReadOnlyCollections.java:15)  

Thursday 26 February 2015

How to find disk space utilization using Java?

 import java.io.File;  
 import java.nio.file.FileSystem;  
 import java.nio.file.FileSystems;  
 import java.nio.file.Path;  
 import java.util.Iterator;  
 public class DiskSpace {  
  public static void main(String[] args) {  
            FileSystem fs = FileSystems.getDefault();  
            Iterable drives = fs.getRootDirectories();  
            Iterator path = drives.iterator();  
            while(path.hasNext()){  
                  Path p = path.next();    
                  String drive = p.toString();  
                  System.out.println(drive);  
                  File f = new File(drive);  
                  float freeSpace = f.getFreeSpace();  
                  float totalSpace = f.getTotalSpace();  
                  if(totalSpace > 0){  
                          float percentFree = (freeSpace/totalSpace)*100;  
                          System.out.println(drive + "---- " +freeSpace + "------ " + totalSpace + "---------- " + percentFree);  
                  }  
            }  
      }  
 }  

Tuesday 24 February 2015

Difference between JSP include directive and JSP include action

@include 
<%@ include file=”filename” %> is the JSP include directive. At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers.


The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output. is the JSP include action element. 


<jsp:include>
The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page.
 When the included JSP page is called, both the request and response objects are passed as parameters. If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

Tuesday 28 October 2014

Java Class Loaders

        Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.



Classloaders and their explaination -  
  • Bootstrap (primordial) - No Loads JDK internal classes, java.* packages. (as defined in the  sun.boot.class.path system property, typically loads rt.jar and i18n.jar). Classes loaded by Bootstrap  class loader have no visibility into classes loaded by its descendants (i.e. Extensions and Systems  class loaders).

  • Extensions - Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
  • System - No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options). The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).


Wednesday 22 October 2014

Hashmap in Java

If anybody asks me to describe “How HashMap works?“, I simply answer: “On principle of Hashing“. HashMap is a Collection which works on principle of Hashing and it uses key and value pairs to store the information and we can get the value if we pass key to the HashMap. You can also say HashMap is fast as it is not synchronized.

HashMap class comes from java.util package and HashMap class extends AbstractMap and implements Map, Cloneable and Serializable interfaces. HashMap is nothing but Hash table based implementation of Map Interface.



What is Hashing

Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

A little about Entry class

A map by definition is : “An object that maps keys to values”. Very easy.. right?
So, there must be some mechanism in HashMap to store this key value pair. Answer is YES. HashMap has an inner class Entry, which looks like this:

static class Entry implements Map.Entry{
          final K key;
          V value;
          Entry next;
          final int hash;
          ...
}

Surely Entry class has key and value mapping stored as attributes. Key has been marked as final and two more fields are there: next and hash.


put() method in hashmap

We need to pass Key and Value object to put() method in Java HashMap. Once we pass the key and value to in put() method of HashMap, HashMap calls hashCode method on key object and use hashcode into own hashing function to find the bucket location. Bucket is the place where Entry object is stored and hashcode is like an address of that bucket. So what exactly we store in bucket? This is very important to understand. Java stores both Key and Value object as a Map.Entry in bucket. These are stored like LinkedList. But why these are stored as LinkedList. As we know we are using the hashcode to find the bucket location but two unequal objects can have same hashcode. So there are chances of collision. So along with value key is stored.


get() methods in hashmap

We need to pass key to the get method which takes the key as an argument and try to find bucket position using the hashcode. Once it finds the bucket using equals function it gets the value and returns it.

If no match is found, get() method returns null.


Key Notes


  • Data structure to store Entry objects is an array named table of type Entry.
  • A particular index location in array is referred as bucket, because it can hold the first element of a LinkedList of Entry objects.
  • Key object’s hashCode() is required to calculate the index location of Entry object.
  • Key object’s equals() method is used to maintain uniqueness of Keys in map.
  • Value object’s hashCode() and equals() method are not used in HashMap’s get() and put() methods.
  • Hash code for null keys is always zero, and such Entry object is always stored in zero index in Entry[].
  • Order in not maintained in hashmap.


What is the load factor in java HashMap and what happens when size of the HashMap exceeds a given threshold defined by load factor?

Load factor of HashMap is is .75 it will act to re-size the map once it filled 75%, so once size exceeds 75%, then Java HashMap re-size itself by creating a new bucket array of size twice of size defined previously for the HashMap ,then it start putting every old element into that new bucket array. This process is also called rehashing because hash function is used to find the new bucket location.

Saturday 12 July 2014

Direct Memory Access Java

Does Java Allow Direct Memory Access

Well, there is a sun.misc.Unsafe class. It allows direct memory access, so you can implement some magic like reinterpret casts and so on. The thing is you need to use hacky reflection approach to get the instance and this class is not realy well documented. In general you need a very good reason to use this kind of tool in production code.
Here's an example how to get it:

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f
.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
 
 
There are 105 methods, allowing different low-level stuff. These methods are devoted to direct memory access:
  • allocateMemory
  • copyMemory
  • freeMemory
  • getAddress
  • getInt - Gets you a value from the memory whose

 

Sunday 6 July 2014

JVM parameters in Java

On the basis of how we specify JVM option it can be divided into two parts, JVM Options which starts with –X and those which starts with -XX:

1) JVM Options that begin with -X are non-standard (thy are not guaranteed to be supported on all JVM implementations), and are subject to change without notice in subsequent releases of the JDK.

2) JVM Options or parameters which are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice also.



Key Points about JVM Options:

1) Boolean JVM options can be turned on with -XX:+ and can be turned off with -XX:-.
2) Numeric JVM Options can be set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).
3) String JVM options can be set by using -XX:=, and usually used to specify a file, a path, or a list of commands.

The command java -help lists the standard options (standard across different JVM implementations) for the Java application launcher. The command java -X can be used to see the Java application launcher's non-standard (X for extension specific to that JVM) arguments.The -X options are non-standard and subject to change without notice. If you wish to detect which JVM arguments your currently running Java application is using, you can try below code.

Read JVM Parameters Runtime

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.List;

public void runtimeParameters() {
          RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
          List<String> aList = bean.getInputArguments();
          for (int i = 0; i < aList.size(); i++) {
                    System.out.println( aList.get( i ) );
          }
}


Brief Introduction to OOP

Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance.

Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc. 

Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code. 

Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods. 

Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object. 

Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time. 

Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object. Know more about Abstract Class

Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented. 

Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime. 


Thanks to Prashant for adding contribution to this post.

How to add BASIC Authentication into HttpURLConnection?

Here is one sample.

...
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
...
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = username + ":" + password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+
encodedAuthorization);
...
//Send post data
...

} catch (Exception e) {
...
} finally {

if(connection != null) {
connection.disconnect();
}
}
}

Thursday 3 July 2014

Hibernate session.get() and session.load()

Actually, both functions are use to retrieve an object with different mechanism, of course.

1. session.load()
It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
If no row found , it will throws an ObjectNotFoundException.


2. session.get()
It always hit the database and return the real object, an object that represent the database row, not proxy.
If no row found , it return null.
It’s about performance

Hibernate create anything for some reasons, when you do the association, it’s normal to obtain retrieve an object (persistent instance) from database and assign it as a reference to another object, just to maintain the relationship.

Tuesday 1 July 2014

Abstract Class

An abstract class is a class that is declared abstract & it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract. All other functionality of the class still exists like with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods and all accessed in the same manner.

Ex-

public abstract class GraphicObject {
            // declare fields 
            // declare nonabstract methods
            abstract void draw(); 
    }


Can an abstract class be final?
No a class cannot be marked "abstract" as well as "final". Marking a class "abstract" means it contains partial implementation of methods and hence depends on its subclasses to provide concrete implementation. Marking the class "final" means that no other class can
extend it and hence abstract classes cannot be marked final.


Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class, constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Also even if you don’t provide any constructor, compiler will add default no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.


Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract, you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.


What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration. All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

public void abstract sampleMethod();

Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.


Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class.



Thursday 26 June 2014

How to config Tomcat to retrieve images from an external folder outside webapps(outside the context of tomcat)?

You should add following line in server.xml file

<Context path="/DataRepository" docBase="D:/DataRepository/" />

You must put this context tag inside of HOST tag.

Now you can just access the image present inside your path "D:/DataRepository/".

For Example if your DataRepository folder is having an image image 'sanket.jpg' then you can access it as ,

http://localhost:8080/DataRepository/sanket.jpg

Wednesday 25 June 2014

HashSet & HashMap

HashSet:

  • HashSet is implementation of Set Interface and extends AbstractSet class
  • Uses Hash table to store the elements.
  • In Hash set the main thing is that objects which are going to be stored in HashSet must override equals() and hashCode() method so that no duplicate value are stored in our set.
  • Contains unique elements only.
  • HashSet is slower than HashMap.
  • Add method is used to add element in Set. public boolean add(Object o)
  • Example : In the HashSet, there must be no duplicate elements.
       HashSet is a set, e.g. {10,20,30}


HashMap:


  • HashMap is a implementation of Map Interface and extends AbstractMap class, which maps a key to value.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.
  • HashMap is not synchronized, but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our HashMap and one thread is structurally change our map.
  • HashMap is faster than HashSet because unique key is used to access object.
  • Put method is used to add element in map. public Object put(Object Key,Object value)
  • Example : HashMap there must not be duplicate keys, but it may have duplicate values.
        HashMap is a key -> value (key to value) map, e.g. {a -> 10, b -> 20, c -> 20}


Differences between HashSet and HashMap in Java
HashSet internally uses HashMap to store objects. When add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy). So it maintain no duplicates because keys are nothing but Value Object. Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

Why add() Method of HashSet return boolean & put() method of HashMap return values?

HashMap put method: Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Return:- the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)



HashSet add method: Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Returns:- true if this set did not already contain the specified element.

Tuesday 24 June 2014

Daemon Thread

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread which runs in background to provide services to the user thread and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
  • Its life depends on user threads.
  • It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Difference between Daemon and Non Daemon thread in Java
1) JVM doesn't wait for any daemon thread to finish before existing.
2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.



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.}