Posts

Showing posts from August, 2011

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…