Sunday, July 13, 2014

Difference between Callable and Runnable in Java

Difference between Callable and Runnable interface in Java is one of the interesting question from my list of Top 15 Java multi-threading questions, and it’s also very popular in various Java Interviews. Callable interface is newer than Runnable interface and added on Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method. Though both Callable and Runnable interface are designed to represent task, which can be executed by any thread, there is some significant difference between them. In my opinion, major difference between Callable and Runnable interface is that Callable can return result of operation performed inside call() method, which was one of the limitation with Runnable interface. Another significant difference betweenRunnable and Callable interface is ability to throw checked exception.Callable interface can throw checked exception because it's call method throws Exception. By the way sometime this question is also asked as follow-up question of another classic difference between Runnable and Thread in Java. Commonly FutureTask is used along withCallable to get result of asynchronous computation task performed in call() method.


Callable vs Runnable interface

Difference between Runnable and Callable in JavaAs I explained major differences between Callable and Runnable interface in last section. Sometime this question is also asked as difference between call() and run()  method in Java. All the points discussed here is equally related to that question as well.  Let's see them in point format for better understanding :


1) Runnable interface is older than Callable, there from JDK 1.0, while Callable is added on Java 5.0.
2) Runnable interface has run() method to define task while Callable interface uses call() method for task definition.
3) run() method does not return any value, it's return type is void while call method returns value. Callable interface is a generic parameterized interface and Type of value is provided, when instance of Callable implementation is created.

4) Another difference on run and call method is that run method can not throw checked exception, while call method can throw checked exception in Java.


public class RunnableTest implements Runnable {
              @Override
              public void run() {
                         //any processing
              }
}
import java.util.concurrent.Callable;


public class CallableTest implements Callable { 
          @Override 
           public String call() throws Exception { 
                      // any processing
                    return new String("I am Callable and can return value and throw checked exception"); 
              } 
}

How to Stop Thread in Java

Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.


How to Stop Thread in Java


How to Stop Thread in Java Tutorial Example
As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java:








Sample Code to Stop Thread in Java



public class Runner extends Thread{
    boolean bStopMe= false;
  
    public void exit(){
        this.bStopMe= true;
    }

// or
   public void tellMeToStop() {
    bStopMe= true;
  }

    @Override
    public void run(){
        while(!bStopMe){
            System.out.println("Thread is running");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }

}
    
    

Should we make bExit Volatile
Since every Thread has its own local memory in Java its good practice to make bStopMevolatile because we may alter value of bStopMefrom any thread and making it volatile guarantees that Runner will also see any update done before making bExit.

That’s all on how to stop thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.


Q: I have been wondering why isn't there a method to kill a waiting, sleeping or a non running thread. Is there anyway we can do that?

A: The reason you can't just stop a thread is actually fairly simple. What if it's allocated resources, and is in the middle of work? If you do a hard stop, that may just leave a lot of stuff hanging. So, instead you basically send it a message and it stops at it's own convenience (if implemented properly). Basically they pushed back that part of the behavior to the programmers.




Saturday, July 12, 2014

Difference between Thread and Runnable interface in Java

Thread vs Runnable in Java is always been a confusing decision for beginners  in java. Thread in Java seems easy in comparison of Runnable because you just deal with one class java.lang.Thread while in case of using Runnable to implement Thread you need to deal with both Thread and Runnable two classes. though decision of using Runnable or Thread should be taken considering differences between Runnable and Thread and pros and cons of both approaches. This is also a very popular thread interview questions and most of interviewer are really interested to know what is your point of view while choosing Thread vs Runnable or opposite. In this java article we will try to point out some differences between Thread and Runnable in Java which will help you to take an informed decision.


Thread vs Runnable in Java


Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as "Callable" for implementing thread which we will discuss later.

1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

These were some of notable difference between Thread and Runnable in Java, if you know any other differences on Thread vs Runnable than please share it via comments. I personally use Runnable over Thread for this scenario and recommends to use Runnable or Callable interface based on your requirement


Tuesday, July 8, 2014

How to write production quality code?

How to write production quality code?
We often here the term "production quality code" , some times in interview where interviewee asked to write production quality code for a particular function,Some time discussion between developers and programmers and some time during code review. I know most of you familiar with term but for those who wonder what is production quality code in simple terms its code which can bear the test of time in production environment.

We all develop code in development, than test in QA and finally it gets released in production. But there are lot of difference between test and prod and if you have not coded taking prod environment in mind most likely code will fail in prod or result in exceptions.So what makes production environment different than development environment? Here are few things which I noted:


1) Production is all about load which will expose concurrency issues, load issues, memory and CPU issues.

2) You will get a lot many scenarios in production that you might have thought in development. If think through process is not applied than most likely those scenario has not handled in production.

3) Different data input or incorrect data, one of classic problems in production is the data which gets input to your program, be it from upstream system or any other place you will get all sort of data and if your program doesn't handle those very likely it will suffer.

4) Boundary conditions, this is some what related to above point data and scenarios but most of the boundary condition e.g. null, empty etc exposed in production.


So if a code is written all these things and potentially domain specific things and can sustain test of production than it called a production quality code and believe me it takes a lot of experience, skill and think through process to write production quality code not just in first time even after two or three iteration but as a developer we should always strive for writing production quality code in first attempt.

Now let's see how we can do that, what are the things we should keep in mind:

1) Get your requirements right, understand the problem , talk to user or business person as much as possible this will help you to find different scenario as early as possible. Many times business or user not tell you everything its not there fault but it doesn't come in mind right through. So if you are frequently speaking, discussing and presenting solution to them most likely they will ask questions, give feedback which eventually expose more scenario and subtle details. Here experience plays an important role. More experience or domain knowledge you, much better code you will write.

2) Think through, Think through and Think through. There is no substitute of this, it is more of a skill and art than science but you will get hold of this when you get more experience. For example if user says that you need replay capability in your program. You should be able to think of all possible scenarios where you need to replay and what could be required for that, what would be side effect of that. Does replay would be requested, what if the requesting system went down again, will you be able to re replay etc.

3) Boundary condition, always think that you will get bad input , you will get null or empty, small or very large numbers, function may get called at wrong time etc. you can get rid of this by writing unit test for each boundary condition.

4) Concurrency, this is is the major culprit and big problem which exposes itself in production when due to load multiple thread gets triggered and access your program concurrently. With high speed low latency electronic trading system and with many other java system where its requirement to have a concurrent application this can only be addressed by proper design , if you get the design right you will safe other wise you will need to bear the pain of redesigning or rewriting code. You can also expose concurrency issue by doing load testing in early QA cycles.

5) Exception handling, this is by far most important characteristic of production quality code, it must be able to handle exceptional scenario in clear cut predefined way. Whole program should never be crashed due to one single bad input or scenario.

6) Recoverable, code should be able to recover itself in case of premature closing or crash.


Also
1.    Code should be expandable. Once in production, enhancement and new requirements r bound to come. The abstract design should allow for rapid development. Developer should keep on mind when coding

2.    Writing locale independent code is also one of quality for production code. These kind of thing should be part of Resources which allows you flexibility to change the language or resource based on locale.


Read more: http://javarevisited.blogspot.com/2011/09/how-to-write-production-quality-code.html#ixzz36tJFKtkm