Friday, July 5, 2013

Threads: Why must wait() always be in synchronized block?

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

This question is more specific to design aspect of java. Why should object.wait() method be called from a synchronized block? Why is this necessary to acquire monitor of the object? Why cannot application ask a Running thread to wait for sometimes? (Very similar to sleep)

As per the accepted answer, wait and notify are used for inter thread communication. When a thread is waiting for nothing, then what specific condition should wake this thread? On what grounds JVM sends a notification to the thread?

In another answer, an explanation is provided with an example.

package com.thread.problem;
public class Information {
                private String message;
                private boolean isAvailToWrite = false;
                public boolean isAvailable(){
                                return isAvailToWrite;
                }

                public boolean isUnavailable(){
                                return !isAvailToWrite;
                }

                public void put(String msg) throws InterruptedException{
                               while(isUnavailable()){
                                                                System.out.println("Producer will wait now.");
                                                                wait();
                                                }
                                                message = msg;
                                                isAvailToWrite = true;
                                                notify();
                }

                public String get() throws InterruptedException{
                                while(isAvailable()){
                                                                System.out.println("Consumer will wait now.");
                                                                wait();
                                                }
                                                isAvailToWrite = false;
                                                notify();
                                                return message;
                }

}

There are 2 threads i.e. producer and consumer. Producer is calling put method to generate the Information, whereas consumer is digesting this specific information.

Now let’s assume things happen in following sequence.

  1. Consumer thread invokes, and makes a call to get method. It checks that nothing is available, and consumer thread enters in the while block.
  2.  JVM starts producer thread here.
  3. Producer thread puts the information and invoke notify.
  4. As consumer has not reached to the wait state, so it does not care about it.
  5. Now consumer has started waiting.
  6. Producer is never invoked after that.

So in this case main will keep running and no output will be generated.

Adding synchronized blocks to the above solution. No thread will be in intermittent state, and producer and consumer will work as expected.

package com.thread.problem;
public class Information {
                private String message;
                private boolean isAvailToWrite = false;
                public boolean isAvailable(){
                                return isAvailToWrite;
                }

                public boolean isUnavailable(){
                                return !isAvailToWrite;
                }

                public void put(String msg) throws InterruptedException{
                                synchronized (this) {
                                                while(isUnavailable()){
                                                                System.out.println("Producer will wait now.");
                                                                wait();
                                                }
                                                message = msg;
                                                isAvailToWrite = true;
                                                notify();
                                }
                }

                public String get() throws InterruptedException{
                                synchronized (this) {
                                                while(isAvailable()){
                                                                System.out.println("Consumer will wait now.");
                                                                wait();
                                                }
                                                isAvailToWrite = false;
                                                notify();
                                                return message;
                                }
                }

}

Now let’s follow the sequence specified above.

  1. Consumer thread invokes, and makes a call to get method. It checks that nothing is available, and consumer thread enters in the while block. It can only exit until it completes its operations. So it will reach to wait state.
  2. JVM starts producer thread here.
  3. Producer thread puts the information and invoke notify.
  4. As consumer is in wait state, so it will awake at notify call.
  5. Consumer will consume the information and notify the producer to generate more information.



 wait() isn't strictly guaranteed to do anything at all. Something called "spurious wakeups" might occur. That is, a call to wait() can
return at any time without any good reason. So a good rule of thumb for using wait() is that you should consider it to be nothing but an optimization. If a program issn't correct already (and assuming that thread starvation is not occurring), calling wait() can NOT make a program correct. However, it certainly can make a program incorrect!

So we need to start out thinking of how we'd write the code without wait at all. So how do you wait for something is wait() doesn't do anything? Easy... you do a busy-wait:

while (!thingImWaitingFor()) /* DO NOTHING */;

This uses 100% of the CPU power available, of course, and performance horribly. The optimization is this:
while (!thingImWaitingFor()) wait();

That explains the need for a "condition", which in this case is !thingImWaitingFor(). Next, you need a guarantee that the
waiter and the notifier agree about the state of the condition.
The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the condition being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program. (Vulnerability has been explained above with the producer and consumer example)

You need that period of vulnerability to be protected by a synchronized block. If the waiter didn't synchronize, then any old bit of code might change the predicate just before it goes to sleep, and then we're certainly in trouble. If the notifier didn't synchronize, then it could change the predicate even though the waiter is holding the lock, and we are screwed.

However, the waiter can't hold a synchronized lock while it's waiting. At first glance, this problem seems impossible. Now, there's actually a bit of magic involved here. The wait() method ATOMICALLY releases the lock and goes to sleep. It's a sort of deus ex machina solution (deus == Java Virtual Machine) to the otherwise impossible problem. 

Thursday, July 4, 2013

Threads: Producer and Consumer Problem

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). This post is a sticky notes post for me.

Problem Statement
The producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate a piece of data, put it into the buffer and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.

Solution
Producer and consumer should produce and consume some resource. For the simplicity purpose I am taking minimalist object in the Information object.

package com.thread.problem;
public class Information {
                private String message;
                private boolean isAvailToWrite = false;
                public boolean isAvailable(){
                                return isAvailToWrite;
                }

                public boolean isUnavailable(){
                                return !isAvailToWrite;
                }

                public void put(String msg) throws InterruptedException{
                                synchronized (this) {
                                                while(isUnavailable()){
                                                                System.out.println("Producer will wait now.");
                                                                wait();
                                                }
                                                message = msg;
                                                isAvailToWrite = true;
                                                notify();
                                }
                }

                public String get() throws InterruptedException{
                                synchronized (this) {
                                                while(isAvailable()){
                                                                System.out.println("Consumer will wait now.");
                                                                wait();
                                                }
                                                isAvailToWrite = false;
                                                notify();
                                                return message;
                                }
                }

}

Information class has 4 methods.

isUnavailable and isAvailable are providing the information whether the Information class can accept more data or provide any data.

put and get are synchronized method, which are setting or retrieving data from the Information object.
In case of get request, if data is not available, then current running thread will go to wait state, and wait until put operation is not performed on the Information object. It holds true for put operation as well.

Now information object must be produced and consumed with different threads. So we will need producer thread to produce information object, and we will need consumer thread to consume the produced objects.

package com.thread.problem; 
public class Consumer implements Runnable {
                private Information pool;
                public Consumer(Information pool) {
                                this.pool = pool;
                }
               
                @Override         
                public void run() {
                                for(int i = 0; i < 20; i++){
                                                try {
                                                                System.out.println("Retrieved String:::: " + pool.get());
                                                } catch (InterruptedException e) {
                                                                e.printStackTrace();
                                                }
                                }
                }

}

package com.thread.problem; 
public class Producer implements Runnable {
                private Information pool;
                public Producer(Information pool) {
                                this.pool = pool;
                }
               
                @Override         
                public void run() {
                                for(int i = 0; i < 20; i++){
                                                try {
                                                                pool.put("String " + i );
                                                } catch (InterruptedException e) {
                                                                e.printStackTrace();
                                                }
                                }
                }

}

Constructors is created so that shared objects can be passed to Consumer and producer thread.
Once everything is set up, now we need to demonstrate whether our solution works. So let write main method within another class which will start both the threads.

package com.thread.problem; 
public class Demonstration {

                public static void main(String[] args) {
                                Information pool = new Information();
                                Thread c = new Thread(new Consumer(pool));
                                Thread p = new Thread(new Producer(pool));
                                p.start();                             
                                c.start();
                }
               
}

Output for the following program will be as following.
Producer will wait now.
Producer will wait now.
Retrieved String:::: String 0
Producer will wait now.
Retrieved String:::: String 1
Producer will wait now.
Retrieved String:::: String 2
Producer will wait now.
Retrieved String:::: String 3
Retrieved String:::: String 4
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 5
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 6
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 7
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 8
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 9
Producer will wait now.
Retrieved String:::: String 10
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 11
Producer will wait now.
Retrieved String:::: String 12
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 13
Producer will wait now.
Retrieved String:::: String 14
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 15
Consumer will wait now.
Producer will wait now.
Producer will wait now.
Retrieved String:::: String 16
Retrieved String:::: String 17
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 18
Consumer will wait now.
Retrieved String:::: String 19

This output may differ from compiler to compiler.

Its indeed a useful design pattern and used most commonly while writing multi-threaded or concurrent code. here is few of its benefit:
 1) Producer Consumer Pattern simple development. you can Code Producer and Consumer independently and Concurrently, they just need to know shared object.
 2) Producer doesn't need to know about who is consumer or how many consumers are there. Same is true with Consumer.
 3) Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item. In fact by monitoring consumer speed one can introduce more consumer for better utilization.

4) Separating producer and Consumer functionality result in more clean, readable and manageable code.

There are other multiple ways to solve this problem. This example is used to for naive users. Users who have started leaning java language very recently. It is helpful for them.

Wednesday, July 3, 2013

Threads: Difference between wait() and sleep()

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

I never delve into the world of threading, so I could not ever make a much difference between wait and sleep but after understanding the wait method, I could make out something.

Java doc

public final void wait() throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the  notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

What is sleep 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 acquired - 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.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(). Wait is called on an object, not a thread; we call this object the "lock object." Beforelock.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.


Example

Wait Example
public class ConnectionPool {
   private List<Connection> connections = createConnections();

   private List<Connection> createConnections() {
     List<Connection> conns = new ArrayList<Connection>(5);
     for (int i = 0; i < 5; i++) {
       ... add a Connection to conns
     }
     return conns;
   }
}

public Connection getConnection() throws InterruptedException {
   synchronized (connections) {
     while (connections.isEmpty()) {
       connections.wait();
     }
     return connections.remove(0);
   }
}

public void returnConnection(Connection conn) {
   synchronized (connections) {
     connections.add(conn);
     connections.notify();
   }
}

Sleep Example: Requirement is to copy files existed at server to local machine. This activity should be repeated in every 5 minutes.
                public void CopyFilesFromServerToLocal() throws InterruptedException {
                                performCopy();
                                sleep(5*60*1000);
}

Difference between Thread.sleep and Object.wait method

Thread.sleep
Object.wait
It is a static method. On calling the method, it will send current running thread in sleep status. T.sleep(1000) and sleep(1000) both will send current running thread to sleep status. ( T is an instance of another thread)
It is an instance method.
Thread does not uses any CPU cycle while sleeping
Thread does not use any CPU cycle while waiting.
Thread does not releases any lock it possesses
Releases the lock of the object on which wait was called. Other locked monitors will not be released by the waiting thread.
This method can be called from non-synchronized block.
This method must be called from synchronized block. Because if block is not synchronized, then no objects are locked.
Sleep is used for Time Synchronization.
It is used in inter-thread communication.
In Lehman terms sleep tells JVM that I’m done with my time-slice, and please don’t give me another one for at least n milliseconds.
In Lehman terms wait tells JVM that I’m done with my time-slice. Don’t give me another timeslice until someone calls notify().

Tuesday, July 2, 2013

Threads: Why are Wait and notify declared in Object class?

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

This question has haunted me for quite a long time, so it would be interesting to understand the reasons to segregate respective methods from other thread related operations.

Java docs say the following
public final void wait() throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

public final void notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.

Let’s try to understand it with one analogy.
One hotel has only one exclusive suite. It is quite popular. As only one couple can occupy one room, so other people enter their name in the wait list until person occupying the room does not check out of it.
So in this case, the room is a shared resource, and person occupying the room is a thread having a lock. Hotel management is JVM. Hotel management shares the key with first client and once he leaves the room, it picks up one client and notifies the chosen client.

Now let’s look at it with another prospective.
Let’s say hotel management does not want to handle this situation, so it provides client’s number, person who is occupying the room, to all the members. All these people call the client residing in hotel. So instead of enjoying the room, he will be busy in managing these calls, and he might probably sue hotel’s management.

There is one way around, hotel management provides client, having the key, the list of individuals who wanted to book the room next, but will any client accept to call other individuals? He will say that I do not care about calling anyone. You do your business and let me finish mine.

So what does about example signify?
It clearly indicates that none of the thread either cares about other threads or wants to be disturbed while performing its own operations. To avoid this scenario JVM tells every thread to wait on an object, instead talking to threads. This is why wait and notify are part of object instead thread.

Introducing new terms i.e. Monitors
The most simple and obvious reason is that any Object (not just a thread) can be the monitor for a thread. The wait and notify are called on the monitor. The running thread checks with the monitor. So the wait and notify methods are in Object and not Thread.

public class ConnectionPool {
 private List<Connection> connections = createConnections();

 private List<Connection> createConnections() {
   List<Connection> conns = new ArrayList<Connection>(5);
   for (int i = 0; i < 5; i++) {
     ... add a Connection to conns
   }
   return conns;
 }
}

public Connection getConnection() throws InterruptedException {
 synchronized (connections) {
   while (connections.isEmpty()) {
     connections.wait();
   }
   return connections.remove(0);
 }
}

public void returnConnection(Connection conn) {
 synchronized (connections) {
   connections.add(conn);
   connections.notify();
 }

}

This is a typical example of consumer producer problem. In this case we have a connection pool which has 5 connections. Now different thread can request for connections, so connection pool must check whether it has capacity to provide one connection or not. If it has one connection, it will provide it else other wise it will ask thread to wait for connections to release. So here thread will wait on connection. In other words it can be said thread is waiting for connections. Same applies in the case of notify. Once any thread releases the connection, that will added to pool and one of the threads will be notified to grab the newly released connection.

Thursday, June 27, 2013

Threads: How to Kill a thread?

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

Java has provided a stop method to stop the thread gracefully, but with time java has deprecated the method. So what can be most convenient way to exit the thread gracefully?

In the link mentioned below Sun has provided the reason to deprecating few important methods.

Thread.stop deprecated???
On calling Thread.stop, thread unlocks all monitors locked. Basically Thread.stop throws ThreadDeath exception, which propagated up in the stack.)

Now monitor might leave objects in inconsistent state. These objects are called damaged objects.
Objects, with inconsistent state, can be viewed and grabbed by another threads, and it can result in program’s unprecedented behavior.

When unchecked exception is thrown, then user must be aware this exception and he must know about the inconsistency in the behavior. Why did this not happen?

Unlike other unchecked exception, ThreadDeath exception is designed to work silently without leaving much information. So it is not possible to know any inconsistent behavior of the application beforehand.

If not Thread.stop, then what?
In the same document two alternatives have been provided. We need to implement one among them for exit/stop/kill a thread gracefully.

Method 1: We must use a variable to identify when thread should be stopped. It is better to use a volatile variable which will maintain the fresh copy of the specific variable.
   
    private Thread blinker;
    public void stop() {
        blinker.stop();  // UNSAFE!
    }
    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

This piece of code must be replaced with the following code.

    private volatile Thread blinker;

    public void stop() {
        blinker = null;// In the stop method, blinker object’s state has been changed.
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {//When application should be stopped, then blinker is null so it will exit gracefully.
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Method 2: This method is more convenient when thread waits for longer amount of time. In this case we need to interrupt the waiting thread. In this case stop method should be replaced with the following code.
   public void stop() {
        Thread moribund = blinker;
        blinker = null;//I have my own doubts about this method, I will test it and confirm it soon.
        moribund.interrupt();
    }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:

    Thread.currentThread().interrupt();


This ensures that the Thread will reraise the InterruptedException as soon as it is able.

Why reassertion is required?
This is done to keep state.
When you catch the InterruptException and swallow it, you essentially prevent any higher level methods/thread groups from noticing the interrupt. Which may cause problems.

By calling Thread.currentThread.interrupt(), you set the interrupt flag of the thread, so higher level interrupt handlers will notice it and can handle it appropriately.

Here is one example.

import java.util.Calendar;

class RunnableImpl implements Runnable {
public void run() {
runSomeCode();
}

private void runSomeCode() {
while(!Thread.currentThread().isInterrupted()){
waitForSometime(1000);
System.out.println("Checking for interruption. " + Calendar.getInstance().getTimeInMillis());
}
}

private void waitForSometime(int i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}

public class TestRunnable {
public static void main(String[] args) {
Thread instance = new Thread(new RunnableImpl());
instance.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance.interrupt();
}
}

Output:
Checking for interruption. 1372386050062
Checking for interruption. 1372386051063
Checking for interruption. 1372386052063
Checking for interruption. 1372386053063
Checking for interruption. 1372386054063
Checking for interruption. 1372386055063
Checking for interruption. 1372386056063
Checking for interruption. 1372386057063
Checking for interruption. 1372386058064
java.lang.InterruptedException: sleep interrupted
Checking for interruption. 1372386058903
at java.lang.Thread.sleep(Native Method)
at RunnableImpl.waitForSometime(TestRunnable.java:20)
at RunnableImpl.runSomeCode(TestRunnable.java:13)
at RunnableImpl.run(TestRunnable.java:8)
at java.lang.Thread.run(Unknown Source)

Threads: Implementing Runnable or Extending Thread

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

Thread can be instantiate with 2 different ways. You can create a class by either implementing Runnable interface or extending Thread class.

public class RunnableImpl implements Runnable {
                public void run() {                      
                                // TODO Write something here.
                }
}

public class SubThread extends Thread {
                public void run() {
                                //TODO  Write something here
                }
}

When java has provided various ways of implementation, then where these implementations should be used. Which is more commonly and beneficial implementation among two?

1.  One basic difference between these two approaches is when class is using an interface then it has the freedom to extend any other class. So RunnableImpl class may have multiple functionalities. Whereas when class extends thread class, then it is bound to function as Thread only.

      2. When class is implementing Runnable interface, then this class can act as a nonthreading instance.
At the start application used to perform in the manner mentioned below.

public class ExecuteRun{
                public static void main(String[] args) {
                                Thread runImpl = new Thread(new RunnableImpl());
                                runImpl.start();
                }
}

But for some strange reasons, it was decided to get rids of multithreading implementation. In this case the following code can be changed to the following.

public class ExecuteRun{
                public static void main(String[] args) {
                                new RunnableImpl().run();
                }
}

On forcing our mind to work, we will say it is possible to do with Thread implementation as well, then why we preferred it over other.
It was preferred because Java 1.4 caused a memory leak when Thread was started with Run method instead Start method.
Though this issue has been resolved in Java 5 and higher versions, but people still prefer other implementation practice.

3. Other important reason to use Runnable is the flexibility to use concurrency API introduced in Java 5. Runnable allows to keep work loosely coupled with desired concurrency.

Caveat: Around here, I strongly discourage the use of raw Threads. I much prefer the use of Callablesand FutureTasks (From the javadoc: "A cancellable asynchronous computation"). The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads.

Follow-up: there is a FutureTask constructor that allows you to use Runnables (if that's what you are most comfortable with) and still get the benefit of the modern concurrency tools. To quote the javadoc: If you don't need a particular result, consider using constructions of the form:Future<?> f = new FutureTask<Object>(runnable, null)

So, if we replace their runnable with your threadA, we get the following:

new FutureTask<Object>(threadA, null)

Another option that allows you to stay closer to Runnables is a ThreadPoolExecutor. You can use theexecute method to pass in a Runnable to execute "the given task sometime in the future."
If you'd like to try using a thread pool, the code fragment above would become something like the following (using the Executors.newCachedThreadPool() factory method):

ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());

4. One significant difference between Thread and Runnable is the sharing of resources. In case of Runnable implementation, one resource can be shared with multiple instances whereas it is not possible with thread implementation. (I will try to find some appropriate example here soon)

Such a huge discussion boils down on the following point.

Subclass must extend a class only if it overrides methods other than Run method, otherwise it is beneficial to implement an interface in the class.