Saturday, April 19, 2014

Overloading main() in Java

A common fresher interview goes like, Can we overloading main() in Java?
It's a very tricky question on the face of it. But if we just recollect basics, it won't be too hard to answer.

Answer is Yes, we can very much do.

By default we use String args[] as the method argument for main(). We can have multiple mains with different arguments types.





Error Cases
1. main(String args[]) is missing



Monday, March 10, 2014

Why we need Threads

As the time progress, man is becoming more and more impatient. In today's world of instant food, we want instant results. Gone are the time of batch processing and waiting days for a result. We like the program to finish execution asap. 

This is the major reason why we need threads. Threads aid in executing the program faster than before.

In real life also we do multiple things at the same time. A background process of breathing/heartbeat goes on while we perform daily chores. In office we type and talk at the same time. Similarly we like our program to do multi-tasking. This is achieve via Threads.



Before are few scenarios when usefulness of Threads become evident.

Case 1: Website and User Experience (Background Processing)
Consider a website running on a single thread. It takes an input from the user. While it is processing that input, what happens to the website? Use sees a hanged website. So much for user experience.

Solution: When website takes and input, a separate thread can work in background and do the processing, while user experience remains unhindered, enriching the overall quality.

Case 2: Query to a Database (Asynchronous Processing)
Consider a database call from a program. While database is taking its time to respond, the program is sitting is doing no processing. This slows down the overall execution.

Solution: Database query can be done by a separate thread, which waits for the result to be back. Overall it looks asynchronous. Program keeps on doing it's independent processing whilst, a separate thread id waiting for the Database results to be back.

Case 3: Multiple Processors
With the advent of multiple processors, single threaded programs are anyways at a loss. Parallel executions can occur in separate processors. To utilize that, multi-threaded code is a must.

Case 4: Simple Code
Just like recursion, which is difficult to understand but code becomes extremely simple. Same is the case with multiple threads. Code becomes extremely simple to write and modular. If we can divide our execution in separate paths, we should go for threads.

Programming example of multi-threading making things easier is Multithreaded QuickSort.


Saturday, February 8, 2014

Multiple threads v/s Multiple processes

A legitimate question occurs that is thread is just like a process, why don't we create multiple processes? Why do we create multiple threads?

There are a few reasons.

Consider it just like an evolutionary process. First there were just processes. It lead to the below shortcomings.

1. If we create multiple processes which should share same resources, coding for it was a cumbersome process. 
2. Memory wise too, creating a new processes requires more resources, than creating a separate thread, as essentials (memory, files etc) are shared by all threads.

It lead to the creation of threads. The code remains a single unit. And multiple sub-processes are spawned. 

You can consider it like, if 2 small packages can be bundled up and send via courier. Why to send two different couriers.

Two different couriers require:
1. Creating two separate records and tracking numbers.
2. Two separate outer packing material is required.
3. Packing material comes in standard size, hence small package are also packed into big envelopes, which is wastage.

Single courier
1. If delivery address is same, it's better to package them together.
2. Single record and tracking.
3. Single packing material and less wastage.

Three Elephants v/s One Elephant and Two rats

Understand it by another example. When we can do with one elephant and two small rats. It is better than three big elephants.



Thursday, January 2, 2014

Primitive Data Types Java

Total 8 primitive types are supported by Java.

Data types is nothing but a way to assign different size of memory space to different data. Depending on the size required to store the data, memory space is allocated to it.

To make things easy, In Java we call such memory spaces by name as below,

Data Type
Size
Default Value
Min
Max
boolean
1 bit
false
false
true
char
2 byte
'\u0000'
'\u0000' (or 0)
'\uffff' (or 65,535)
byte
1 byte
0
-128 (-2^7)
127 (2^7 -1)
short
2 byte
0
-32,768 (-2^15)
32,767 (2^15 -1)
int
4 byte
0
- 2,147,483,648 (-2^31)
2,147,483,647 (2^31 -1)
long
8 byte
0L
-9,223,372,036,854,775,808
(-2^63)
9,223,372,036,854,775,807
(2^63 -1)
float
4 byte
0.0f


double
8 byte
0.0d




Wednesday, October 9, 2013

WAIT() NOTIFY() SHORTCOMING: SINGLE WAIT QUEUE

There is an inherent drawback of wait(), notify() methods in Java.
As we are aware every Object in Java is associated with a Entry Queue and a Wait Queue. When a thread reaches a synchronized block, it will wait on the Entry Queue of the Object if any other Thread already has the lock. Once it acquires the lock, does its processing, calles Object.wait(), it waits on Wait Queue of the Object. When some other Thread calls Object.notify(), one of the threads waiting on the Wait Queue is moved to the Entry queue of the Object, where it fights for the lock on the Object (with all other Threads waiting at the Entry Queue).
The shortcoming is that wait is not a conditional wait. Every object has just one wait queue.
So if a Object.notify() is called, of all threads waiting on wait queue, any one thread at random is moved to the entry queue. There is no direct way to notify a particular Thread. What we do is a workaround. Instead of Object.notify(), we call Object.notifyAll(), so as all threads are moved from Object’s wait queue to entry queue. Object.wait() call is made in a while loop each checking on a particular condition. So we attach each Object.wait() with a particular condition, as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
//Thread1
synchronized(object) {
    while(!condition1) {
        object.wait();
    }
}
//Thread 2
synchronized(object) {
    while(!condition2) {
        object.wait();
    }
}
When some other Thread sets condition2 = true (while condition1 is still false) and calls object.nofityAll(), both the above Threads which are waiting on the wait queue of the object, are moved to entry queue of the object. Since wait() is in spinning while loop, so Thread1 (if it gets the lock) again calls object.wait() while the Thread2 (if it gets the lock) comes out of the loop starts the processing.
The drawback you see, is unnecessary processing (looping once and checking for condition) in Thread1 and also unnecessary moving of Thread1 from wait queue of Object to entry queue to back. Thread1 wanted to awaken only ifcondition1 == true and Object.notify() is called (not just @ Object.notify()). What would have been nice if there was provision for Conditional Monitor Objects with each having its own wait queue. Something like,
1
2
3
4
5
6
7
8
9
//Thread 1
synchronized(object) {
    object.wait(condition1);
}
//Thread 2
synchronized(object) {
    object.wait(condition2);
}
Here wait is now waiting on a condition. I have seen some good implementations which are provided  for above problem. One being here.