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.

Wednesday, June 5, 2013

Difference between antcall and depends

Sometime we work without thinking much about the build script and other times we need to change the build scripts. At this time we start thinking about various functions in the language.

So today when I was modifying such build script, then I got stuck between the use of "depends" and "antcall". I did little bit of Googling and I got 2 nice articles.

It is not possible for me to elaborate all the uses of ‘depends’ and ‘antcall’ but I will try to provide little information on these targets.

Depends is an attribute of “target” target.

<target name=”runtarget” depends=”target1, target2, target3”  if="condition">

About specified line says before running “runtarget”, ant must execute target mentioned in the “depends” attributes. If condition is verified once all the targets mentioned in the “depends” attribute have already run.

So execution order will be as follows:
1.                   target1
2.                   target2
3.                   target3
                if(condition == true)
4.                   runtarget
                endif

Let’s take another example.
<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

In this case if target D is executed then it will run in the following order.
A -> B -> C -> D
In this case target will not be executed twice.

‘antcall’ is a target/task. It invokes another target which exists in the build xmls.

<antcall target=”target1”/>

In this case processing will switch to another target specified in the antcall. Let’s look at the an example to illustrate the functionality.
<target name=”target1” />
<target name=”target2” >
<antcall target=”target1”/>
</target>
<target name=”target3” >
<antcall target=”target1”/>
<antcall target=”target2”/>
</target>

Now on invoking target3, following will be sequence of run.
Target3 -> target1 -> target2-> target1

As you can see, target 1 is run twice as it will called by target 3 independently and target 2 also invoked target 1 internally. Whereas when such duplicity exists in target called by depends attribute, then ant resolves such duplicate target.

Uses of antcall and depends in one example
Requirement: I have to build a project and create a jar file. Building of this jar depends on already build 100+ jar files, which are at some remote location at the starting of the project. If these jar files do not exist locally, ftp these jar files from remote location.

Approach 1: We will copy the jar files irrespective of their existence.
Approach 2: We will check whether jar files exists, if not then we will copy them from server.

Solution:
Approach 1 is not only time consuming but also it involves the risk of copying the file from remote location, which may not exists at time.
Approach 2 is efficient and nice. So let’s write the code for this.

<target name=”CopyJarsFromServer”>
<!—code for copying the jar using ftp -->
</target>

<target name=”validatejars”>
<if condition>
<antcall target=”CopyJarsFromServer”/>
<!—these is not other way to do it without using ant call -->
<end if>
</target>

<!—We are using depends attribute as we want to make sure that jar exists before any actual processing starts -->
<target name=”build” depends=”validatejars”>
<!—relevant code to build the jar -->
</target>

Hurrey, Now I understand the difference between antcall and depends, and I hope you too. J

Misuse of antcall task may hamper efficiency of your build script as antcall task does allow you to control what properties and references are defined (which is why a new Ant environment is created--and why it's so slow) so it can be used to create variants of the same thing; e.g., maybe two jars, one with and one without debug symbols.

So use antcall task only if it is not possible to find a workaround using depends target.

If you didn’t like my explanation and wants to check actual links that I have used to understand the difference, then please visit the followings