24 April 2010

Threads Execution - From my Imagination

Having posted general posts for long time, once in a while, a little poor programmer tries to creep out. This is an interview question and so far I haven't heard from anyone any different answer. The key to software development is imagination and trying to add more perspective. The multiple perspective helps us to clearly differentiate and appreciate the depth of the language. With no delay, let me jump into my question. Take a look at the following code and tell me what happens.
public class Threads extends Thread {
   
    public void run() {
        // do some serious thing
    }
   
    public static void main (String[] args) {
        Threads t = new Threads();
        t.start();
        t.start();   
    }
}
If you recognized that we create a thread, execute it twice and it will lead to IllegalThreadStateException, you are right. But have you ever imagined why threads cannot be executed twice. Here is my imagination.

Any thread is an independent execution path. You can have many execution paths that are similar in terms of execution and state changes. Let us take an example from real world. We do lot of things in a day like reading, writing, eating, speaking and so on. If we model or think that each activity as thread, though on a given week we may read many times, probably the same book at same speed, each read is different in the context of time. Similarly, in programming, two or many threads appear similar but they are not really similar. Any execution may it be a process or thread, it is illogical to go back in time however you can spawn off new process or thread that does the same thing. Execution cannot be taken back in time (if we take back execution, it is debugging).

Thread has two properties - object and an entity that can be scheduled. The points we discussed above is more on "an entity that can be scheduled". An entity that has completed its run, cannot brought back to execution as its purpose of its creation is over. But from object's perspective, it is data and hence can be accessed and kept for any duration as long as the process is alive.

When you think about thread, remember - "thread has life and object has space". Thread is an object and hence it is given a space in heap, it is available as object till it is garbage collected. But Thread as a entity of execution, it has life. Once its life is over it can be restored again.

No comments: