Tuesday, 3 June 2014

The Advantages and Traps of Autoboxing

What is ‘autoboxing’ some people might ask?
Autoboxing is a feature, which was added in Java 5. Autoboxing is the automatic conversion of primitive data types like int, double, long, boolean to its wrapper Object Integer, Double… and vice versa. So they can be as Object e.g. in Collections.
For example:
1
list.add(5);
In Java 1.4 you had to write for the same result:
1
list.add(Integer.valueOf(5));
(The primitive types must be converted first, because a list can only contain objects.)
Advantages?
  • Less code to write.
    • The code looks cleaner.
  • The best method for conversion is automatically chosen, e.g. Integer.valueOf(int) is used instead of new Integer(int)
Disadvantages
1. Can lead to unexpected behaviour
The usage of autoboxing can lead to difficult to recognize errors. Especially if you mix wrapper with primitives in ‘equals’/’==’.
For Example this:
1
2
3
Long l = 0L;
System.out.println(l.equals(0L));
System.out.println(l.equals(0));
Results into
1
2
true
false
2. Hiding
It hides the object creation, which can lead to a big performance loss. For example:
1
2
3
4
Integer counter = 0;
for(int i=0; i < 1000; i++) {
    counter++;
}
What does ‘counter++’?
It gets the primitive int of the Integer and adds one, that it converts back to a “new” Integer (not necessarily, if the Integer cache contains this Integer).
In Java 1.4 it would look like:
Integer.valueOf(counter.intValue() + 1)
3. Overloading
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) throws Exception
{
Integer l = 0;
fubar(l);
}
static void fubar(long b) {
System.out.println("1");
}
static void fubar(Long b) {
System.out.println("2");
}
The result is 1. Because there is no direct conversion from Integer to Long, so the “conversion” from Integer to long is used.
4. NullPointerException
You can get a NullPointerException, if the wrapper object is null and is unboxed. Pointing out the obvious there can’t be a NullPointer  with primitive variables, but they can have the value zero.
For example look at the code below. In this little example it seems obvious that there can be a NullPointerException. But let’s face it in real code these are only two lines in possible hundreds of lines of code.
1
2
HashMap<String, Integer> map = new HashMap<String, Integer>();
int x = map.get("hello");
Conclusion
IMHO “Autoboxing” is too unexpected in its behavior and can easily result in difficult to recognize errors. Further more the performance loss on unnecessary Autoboxing is too big to ignore. Only for the purpose of clean code this is much to ignore. I would suggest to use it are in simple JUnit tests, where you enter many hard coded numbers(You can ignore the warning with @SuppressWarnings annotation, which is one option of the eclipse hotfix). Or in simple application where you don’t handle with many data like you usually do in a JEE application.
I myself stumbled across one of these errors in an simple “if”. But I don’t know anymore, how the error looked like. A other completely independent team in our company had a similar experience and they forbid to use Autoboxing in their project, too.
You can configure eclipse in the compiler options, that using autoboxing produces warnings.
Java->Compiler->Errors/Warnings->”Potential programming problems”->”Boxing and unboxing conversions”

Saturday, 31 May 2014

What is the difference between sleep(), suspend() and wait()?

Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. 

Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). 
A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. 
t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. 

object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." 
Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. 

Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

What is thread pool? Why should we use thread pools?

A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool
  • Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.
  • You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).
Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

Sunday, 25 May 2014

What is a thread leak? What does it mean in Java?

Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.

Q:How can I trace whether the application has a thread leak?
Ans:If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways:
  • Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads.
  • Change debugging config levels (debug, info, error etc) and analyze log messages.
  • When you find the class that is leaking out threads check how new threads are instantiated and how they're closed.
  • Make sure the thread is Guaranteed to close properly by doing following - Handling all Exceptions properly.
  • Make sure the thread is Guaranteed to close properly by doing following
-Handling all Exceptions properly.
-releasing all resources (e.g. connections, files etc) before it closes.