Posts

Showing posts from 2011

How does HashMap work in Java

We all know and must have used HashMap, its a Map interface implementation. It stores keys and its corresponding value. Keys cannot contain duplicates and can contain at the most one null key (HashTable does not allow null as key, FYI). It has non synchronized methods unlike HashTable. It does not guarantee the order of retrieval (it changes every time the HashMap is modified) etc etc. Enough of this now..


So how does HashMap work?
Basically when this question is asked it generally means how is the object stored and retrieved from the     HashMap. But of course with the get and put methods in the Map API. Easy isn't it, but that is not what
meets the eye. We need to understand what goes inside to understand the answer to the title of this topic.

So what happens when you put a key/value pair in the HashMap, Firstly, hashCode of the key is retrieved and supplied to hash function to defend against poorly constructed hashCode implementation; to get a new hash value. This value is then …

Immutable classes

An object is said to be mutable when the state of the object can be changed E.x. through the setter methods mostly (of course there are other alternatives to change the state, which we will understand once we step through the guidelines of creating an immutable class). Immutable objects are objects whose state cannot be changed after they are created. Once created their state remains the same till the lifetime of the application (rather every life of the application).


Why would one create an immutable objects?  


Immutability objects find their use in concurrent applications/ multi-threaded applications, such an object is always thread safe which means threads wont see an inconsistent state of such an object,so you don't have to synchronize access to them across threads.They also are good candidate in Hash based collections like HashSet  (they need to override equals and hashCode methods). You can freely share and cache references to immutable objects without having to copy or clone …

Equals and hashcode method

are two of the most important non final methods in the Object class which if not coded properly can lead to problems when used in collection and are difficult to detect and debug. Hence it is important to understand the contract of the two methods to code for the same.
Equals method, defined in the object class checks if the references of the objects are the same, i.e they point to the same memory location. You can override this method to check if the two objects are meaningfully equivalent (though residing in different memory location). The following contract needs to be observed while coding the equals method

Reflexive - o1.equals(o1), an object should be equal to itselfSymmetric -  o1.equals(o2), if and only o2.equals(o1)Transitive -  o1.equals(o2), and o2.equals(o3) implies o1.equals(o3)Consistent - o1.equals(02), returns the same result as long as the objects are not modified.Null Comparison - !o1.equals(null), which means any object is not equal to null, it should return false.Eq…

How to make classes thread safe ?

What is Thread safety?
Thread safety is not making a class which implements Runnable or extends Thread, safe.  Thread safety means that the fields of an object or class always maintain a valid state as observed by other objects or classes when used concurrently by multiple threads.


What are the problems if you don't make a class thread safe?
Consider a scenario, where two threads are working on the same instance of the class. The object may be undergoing some modification in one thread and at the same time another thread may try to view the state of this object. This object when in thread1 could be in some intermediate state (when it is pre-empted) when thread 2 tries to access it. In this situation, thread 2 is viewing dirty state of the object. To make two threads, view a valid state of the object is when we term that an object is Thread safe.

When should you think about thread safety?
Firstly, you should think of thread safety whenever you are working in a multi-threaded applicat…

All about Exceptions

What are Exception? Well, exception are exceptions, they are not normal and suggest that they should be handled in order for you to proceed forward or else some can be severe that they can cripple your application.

What are the different types of exceptions?
Exceptions - are the not so serious types of problem in your code. Some are ones which are known and hence compiler wants you to handle them and take corrective action, these are called checked exceptions and some are unknown at compile time and are hence called unchecked exceptions. Exceptions like ArrayIndexOutOfBoundsException are unchecked exception as they happen at runtime and hence are also termed as RuntimeException.
Errors - are more fatal, they can bring down your application, you cannot catch them. OutOfMemoryError is once such example, it means that JVM cannot allocate an object because it is out of memory.

Some points to remember about exceptions

All Exceptions are derived from java.lang.Exception or its subclassYou can cr…

Serialization in Java

In my previous post about cloning there was a mention of serialization. So,
What is serialization? It is the process of reading or writing an object to a stream. Here the object's state is written to a sequence of bytes, this transformation is called serialization. The object state can then be retrieved from the stream of bytes into a live object for use later in the program. This process is called de-serialization.
What can or cannot be serialized? The variables which are marked as static or transient are not serialized all others can be. Static variables are not serialized as the don't belong to any individual object of the class, where as transient construct lets the programmer control which variables need not be serialized. So what happens to these variables when the state is de-serialized; these variables will get the default values.
When and why would one need serialization? Serialization has found its uses in many places As mentioned in the post for 'Deep cloning and Shall…

Type casting - Implicit and explicit

The basics
Whenever you create a class in java, you create a new data type. You can create instances of these classes  which are referred to as objects. To work with the objects you would need a variable through which you refer the objects, these are called as the reference variable and the object that the variable refers to is called the referred object.
Creating a reference variable with the java statement          Employee employee;  (In general ReferenceType reference) will not create an object of Employee instead it will just mean that we have created a reference variable for an object of type Employee.
This reference can hold the value of null or an object of ReferenceType  or any object whose type is subclass of ReferenceType.The reference type could be a interface/abstract class/class. The type of the reference determines how the referenced object i.e the object that is the value of the reference can be used,(you can use the behavior of the referenced object or its superclasses i…

What do you mean by deep cloning and shallow cloning

Java supports two different types of cloning
Shallow cloning - java's object.clone() gives a shallow copy of the object being cloned. Here the object cloned is copied without its contained object. Shallow cloning is a bitwise copy of an object. New object is created which is an exact copy of the original one. In case  of contained objects just the references are copied.Deep cloning - as object.clone() method yields shallow copy, to achieve deep copy classes needs to be adjusted (check note below). Here the original object is copied along with its contained objects (note: here the entire graph of objects are traversed and copied.) Each object in the graph is responsible of cloning itself through the clone method.So, In deep cloning, complete duplicate copy of the original copy is created. NOTE:  If the object wants to be able to clone itself it first needs to implement Cloneable interface else object is going to throw CloneNotSupportedException when the clone method is called. Second…

Garbage collection in Java

What is garbage collection and who handles it?
is the process of collecting unused/unreachable objects (i.e those objects who have lived their life in the lifetime of a program and whose non existence does not affect the continuity of the program). Java handles memory de-allocation through garbage collection. There is a low priority daemon thread called the Garbage Collector thread which runs in the background performing this task of collecting unreachable objects. It runs in low memory situations to reclaim unused memory. Garbage collection cannot be forced, you can request the JVM to perform GC through System.gc(), but there is no guarantee that it will be a synchronous call or it will happen immediately on call.


Why does GC happen?
Whenever the JVM runs low in memory /or during certain time intervals, the garbage collector thread will wake up and try to reclaim unused memory by de-allocating memory referenced by unreachable object. Every programmer must have experienced a behavior o…

How does JVM handle synchronization?

Introduction
We have seen how the JVM organizes the program into runtime data areas in my previous blog. We know that each thread has its own stack and that all the threads in the program share the heap. The heap contains all the objects created within the program including the thread. The method area contains all the class /static variables of a classes used by the program. These variables are available to all the threads in the program.

Now we know that we have two data areas which contains data shared by all threads.
1. the heap and 2. the method area

Monitors
So if two threads try to access the objects or class variables in these areas concurrently, then the data need to be properly managed else we will end up with inconsistent data. This situation can be handled through synchronization and java manages this through the use of 'monitor'. Hence monitor acts as a guardian over a piece of code, so that no two threads execute that code simultaneously.
Java's monitor support…

Synchronization in Java

What is synchronization? Threads communicate with each other by sharing access to fields and the objects reference fields refer to. (concurrent access to shared data).Though efficient, it can lead to thread interference and memory consistency errors. The tool to avoid these kind of errors in java is synchronization.

Why do we need to synchronize?
As said earlier, to avoid
Thread interference: happens when two methods/operations running in two different threads but acting on same data, interleave.(i.e the sequence of steps interleave)Memory consistency errors:  occur when different threads have inconsistent views of what should be the same data.Through the use of synchronization we can avoid the problem of  dirty data (This happens when the shared object is mutable) caused by multiple threads acting on the same data.  To avoid this, java uses monitors and 'synchronize' keyword to control access to a mutable shared object. Synchronization is not needed if you are using an immutable…

Threads in Java

Image
What is a thread?
Thread is a lightweight process i.e single sequential flow of control within the JVM process (when you run the java command at the prompt it creates the JVM to run the application; the name of which you supply as parameter to the java command Ex. java com.test.MainApplication).This process can have multiple threads created within.
As discussed in my previous blog article, a thread shares the heap (place where the object created within the application resides) belonging to the process and has its own stack space. Multiple threads share the heap and hence care should be taken than the objects accessed are thread safe.

Ways to create thread?
There are two ways to create thread
Extend Thread class : and override the run method from Thread classImplement Runnable interface: It has one method public void run() which the implementing class should define.One should implement Runnable interface to get threading behavior instead of extending Thread. One should extend Thread only…

Best practices while using collection API

The following are some best practices that one can follow while using collection API (as discussed in various blogs and books)

Code to interfaces rather than implementation; reason, you can change the implementation later on without significant effect.Set the initial capacity of the collection appropriately, if you know the size you can gain on speed, else these collection classes will have to grow periodically when the size hits the limit.Use ArrayList, HashMap etc as opposed to Vector and Hashtable; reason,Vector and Hashtable methods are synchronized, if you want synchronization using ArrayList, HashMap then you externally synchronize the same. I will show that in my next blog.Return zero length collection or array as opposed to returning NULL; to avoid running into NullPointerException issues at runtime.Immutable object should be used as keys for the HashMap; so also as values in a HashSet. Encapsulate collections; to avoid unintentional  modification of the collections.Stored rela…

Overriding and overloading a method

So what do we understand by these two terms.
Overriding, lets you define the same method in different ways for different object types in an hierarchy (i.e  when there is inheritance, hence we can say a subclass can override the behavior defined in the super class). The general rules to override a method are The method MUST have the same argument list.The method MUST have the same return type.The access modifier CANNOT be less restrictiveThe new method should not throw new and broader exceptions; it can throw less, narrower and run-time exception. If you throw broader exception; you violate the contract defined in the super class and and also you will loose the message the actual exception has to offer  Selection among overridden methods is dynamic (decision at run-time based on the object type).In overloading,overloading lets you define the same method in different ways for different data in the class or its subclass. The general rules to overload a method are.
The method MUST have diffe…

Comparable versus Comparator

Comparable and Comparator are both used to compare objects.
In case of Comparable interface, The object o1 (class of which implements the interface) is compared to the object o2 which is passed as method argument[NOTE: public int compareTo(Object o2) ]If the o1 is greater than o2 then the method will return +ve integer and -ve if lesser than o2, if both are equal then 0 value is returned.It should be used when you want to define natural/default ordering of a class, if the class is available for modification (remember? a third party class isn't available for modification)if one add two keys a and b such that (!a.equals(b) && a.compareTo(b)==0) to a sorted set that does not use an explicit comparator, then the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective. In case of Comparator interface, The Class which implements this interface will take two objects and compare them wi…

Abstract class and interface

When to create abstract class?
We create an abstract class when there is some common behaviour which can be reused across subclasses and certain behaviour needs to be defferred to the sublasses as they are subclass specific. We define such a behaviour using the abstract construct in java. Abstract classes help us achieve implementation inheritance.
When to create an interface?
When the client is only concerned with the behavior and does not worry about the actual implementation, then we should model such behavior using interface. Interface helps us achieve polymorphic interface inheritance.

So having said that,
Abstract classes should be used when there is a strict heirarchy of classes i.e there is strict IS-A relationship between the classes. Ex FlatFileReader/XMLFileReader extends FileReader method loadFile is common behaviour and the procedure to load a flat file versus a XML file is the same however readFile can be sublass specific given the file types. With interface you can relate…

Inheritance versus composition in Java

are two important concepts you should swear by. Both help us to relate classes and achieve code resuse. But which one do we use?
Comparing inheritance and composition.
In inheritance, a change to the method interface/definition of the superclass ripples down to the sublasses (if the method is overriden) and also to the clients of the sublasses thus making the superclass very fragile. In case of composition the change is limited to the containing class and not the clients.With inheritance, you cannot change the overriden method in the subclass without changing the superclass; reason it wont compile. With composition, you can change the interface of the method in the containing class that uses the method/behaviour of the contained class without touching it.In case of inheritance the classes are bound statically at compile time or as soon as the subclass is defined and will remain with the subclass till its lifetime. where as in case of composition, the behaviour can be changed at runtime.…

Class Loaders - simplified - part 2

In my last post I said I will be discussing about NoClassDefFoundError and the ClassNotFoundException
You can load the classes in two ways one is static loading and second way is to dynamically loading the class. Static loading - load a class statically using the new operator.Dynamic loading - programmatically loading the class using the class loader functions at run time.Using Ex Class.forName/ClassLoader.findSystemClass/ClassLoader.loadClass You can get NoClassDefFoundError for the following reason 1) You have not set the class path, so the class loader cannot find the .class file ( TestClass) 2) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class (the call to the new operator fails) 3) It could also happen if the class fails to load as the static initializer block fails for some reason.

You can get ClassNotFoundException if 1) You have set the class path, but the class path does not contain the .class file/jar does not…

Class Loaders - simplified - part 1

Image
As discussed in my previous post, class loaders is one of the components of JVM. It is responsible for finding and loading the class at run time.
Classes are loaded into the JVM as they are referenced by name in a class that is already running in JVM. The first class is loaded into memory by invoking the static void main method of the class. All subsequent classes are loaded by classes which are previously loaded and running.
The following class loaders are created by the JVM Bootstrap or primordial class loader: Is the default class loader which is associated with the JVM. You can hook your own custom class loader instead of the default. All the JDK internal classes java.* packages i.e the ones that belong to rt.jar or i18n.jar are loaded by this class loader. (as defined in the sun.boot.class.path system property)Extension class loader: loads classes that are part of the extensions directory typically the lib/ext directory of the JRE are loaded by this class loader. (as defined in the…

JVM

Java Virtual machine -is an abstract computing machine. It is the component of java technology that gives it hardware and OS independence. It has its own instruction set and manipulates various memory areas at run time.
The architecture as defined in the specification makes it possible to have different JVM implementation for different hardware platforms.The architecture of the JVM as defined in the specification is shown in the diagram below
It consists of Class Loader subsystemRun time data areasExecution engineNative method interfaceNative method libraries.Class loader subsystem - is responsible for loading types (classes and interfaces). The .class files adhere to fix format and it contains JVM instructions or byte codes, a symbol table and other ancillary information. Execution engine - is responsible for the actual execution of the instructions contained in the method of the loaded classes. Run time data areas - the JVM organizes the memory it needs to execute a programs into vari…

Java Platform

is a platform for java development. It is a software only platform which is ported on hardware platforms It comprises of two major components JVM - Java virtual machine - it is the component which add portability aspect to Java. JVM understand byte codes (compiled .class files from .java classes). Byte codes are the machine language of the JVM. JVM then interprets byte codes to the actual underlying machine language. Compilation happens only once and interpretation happens each time the program is executed.Java API - a set of classes written using java and which runs on the JVM. It consists of lot of useful classes which help us in development of applications etc.You can find useful references http://download.oracle.com/javase/tutorial/getStarted/intro/definition.html

Concurrent call exception using Seam and JSF

I got this exception, while working on a Ajax+JSF+Seam project. I ignored it for a while till it came back haunting at the UAT.
A little investigation into the exception and googling help me find the answer. Here is what happened, I had a ajax component which was taking a long time to render the response, in the meanwhile another request was sent to the server through some other component action ex a submit button, this call failed to render the response, reason being the first call had obtained a lock in the render_reponse and hadnt released it, so the second call failed to obtain a lock and hit back with the exception.
You could solve this in one of the following ways,
1. Showing a wait dialog so that the users understand that there is some processing going on.
2. queueing the request, a4j has a component named 'queue' which you can leverage.

If there are better ways to handle this, I will be glad to add it to my kitty.