Tuesday, November 11, 2014

Handler and thread mechanism android

STEP 1: Create a worker thread

class MyThread extends Thread {
    @Override
    public void run(){
    }
}

In our main thread...

MyThread mThread = new MyThread();
mThread.start();

When you have to pass any messages to a thread or get messages from a thread, the receiving thread needs a MessageQueue. By default, a thread created by using the java.lang.Thread class will not have a MessageQueue associated with it. Its just a plain old thread as in the Fig. 1 (Yes, I know. What an innovative diagram !! :D ).




Now, we need to attach a MessageQueue to our thread. The Looper class provides the method prepare() to create a message queue for a thread. We need to call this method from the receiving thread's run method.


STEP 2: Call the Looper methods


class MyThread extends Thread {
    @Override
    public void run(){
           Looper.prepare();
           Looper.loop();
    }
}



As you see, there is one more Looper method called in the code. This loop() method will start running the message loop for the current thread. In simple terms, it will start looking at the MessageQueue and processing the messages. This is how I interpret the Looper as in Fig. 2.



But, who sends the messages to the MessageQueue and how are these processed ? There is a class called the Handler. The Hander allows us to send and processMessages (as well as Runnable Objects) associated with the thread's MessageQueue. So, we need to create a Handler. It is important to note that the Handler is associated with the thread that creates it ! The Handler provides methods to handle (receive) Messages as well as send and schedule messages. For details, please refer to documentation.



STEP 3: Create a Handler to receive the Messages

class MyThread extends Thread {
    public Handler mHandler;

    @Override
    public void run(){
           Looper.prepare();

           mHandler = new Handler() {
                   public void handleMessage(Message msg) {
                       // Act on the message
                   }
           };
           Looper.loop();
    }
}

If you notice, this code is the same that is listed on the Looper documentation page here.  Few things to mention here are. The Handler is created in this thread, hence it is associated with the default Looper (read MessageQueue) in the current thread. There are constructors for the Handler that allow us to specify the Looper (again, read MessageQueue). This allows us to write a cleaner code by writing the Handler class separately and passing on a Looper (again, again, read MessageQueue) when the Handler is created. I'll get to this in a while. But as I have insisted, it is worth noting that whenever the developer documentation refers to a Looper, you can assume they are talking about a queue. I'm really not sure why they have surfaced the Looper class. It creates more confusion (at least for me). Also, when dealing with passing the messages, with this mechanism, we really need not care of the MessageQueue call. That is the reason I haven't linked it to the documentation. Anyways... things are what they are ! For me, I like to interpret this whole mechanism as depicted in Fig. 3.


Let me know if you like PAT or your way of viewing it !

So, now any other thread having the reference to mHandler will be able to call the send or post methods of the Handler class to send a Message (or a runnable object) to our thread. The code for sending message will look like:

Message msg = Message.obtain();
msg.obj =  // Some Arbitrary object
mHandler.sendMessage(msg);

Pretty simple yeah ! Btw, there are various methods to set/get data for the Message object which can be found in the developer documentation for the Message class.

Summary of Steps :
1. Create a Handler in the receiving thread [If it is the main thread, create one in the main thread]. By default the handler will be associated with the default queue (Looper).
2. So, if the receiving thread is created by using java.lang.Thread, then we need to call the Looper.prepare() and Looper.loop() in order to set up the message queue for the thread.
3.  In the sending thread, prepare a message object (or a Runnable object)
4. Get a reference to the Handler in the sending thread and call the send/post methods on it to send a message.

HandlerThread:
Since by default java.lang.Thread doesn't contain a message queue (Looper), Android provides a class called as the HandlerThread which already contains a message queue. The only difference in using the HandlerThread class over the method described above is that you need not call the Looper.* methods.

On creation of a HandlerThread, Android will create a thread containing the looper. So, in the main thread the code will look like:

HandlerThread myThread = new HandlerThread("Worker Thread");  
myThread.start(); 

We separately create a Handler as follows:

class MyHandler extends Handler { 
    public MyHandler(Looper myLooper) { 
        super(myLooper);
    }
    public void handleMessage(Message msg) { 
    }

Now in the main thread, we get the looper for the HandlerThread and pass it when we create the Handler as follows:

Looper mLooper = myThread.getLooper(); 
MyHandler mHandler = new MyHandler(mLooper); 
Whenever we want to send a message from the main thread, we do it in a similar fashion.

Message msg = mHandler.obtainMessage(); 


msg.obj =  // Some Arbitrary object
mHandler.sendMessage(msg); 


I like to visualize this as shown below in Fig. 4 where we write the Handler separately and then pass a looper to it on its creation.












   @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new Thread(new Runnable() {
        public void run() {
            Handler handler = new Handler();
        }
    }).start();
The above code will have error:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Because the thread you're trying to attach the Handler on, doesn't have a looper. And so the constructor of Handler class is throwing exception. You could have used a HandlerThread class instead, This is just a handy class provided by the Android framework.
Please read below for whats happening under the hood.
Lets first try to discuss all parts individually.
  1. Thread:
a. A thread is just a execution flow. A thread by default is suppose to just execute its runnable(if provided) or call its run method. Upon calling new Thread.start(). A thread just dies and Gc'd when the run method executes all the statement written inside the run(){ ---- }.
b. There is a concept of Looper in Android. Which basically makes the thread a blocking thread. Putting simply it just doesn't let the thread die. It goes in a blocking state and waiting for more messages to again resume its execution.
Below is how you'd setup a blocking thread i.e a thread with a looper.
  new Thread(new Runnable() {
    public void run() {
        Looper.prepare();
        Looper.loop();
    }
}).start();
Here a thread is created which doesn't just die after executing the Looper.loop() statement. Instead it loops and goes in a blocking state. Now you must be asking what is the meaning of blocking state, how the thread will come out of the blocking state ? how do i finally release this thread now ? This is where Handler comes in
  1. Handler:
a. It always attaches itself to the Looper of the thread, on which its instance is created.
b. It then processes those messages of the thread it attaches to.
Putting together thread and handlers.
new Thread(new Runnable() {
        public void run() {
            Looper.prepare();
            handler = new Handler();
            Looper.loop();
        }
    }).start();
a. How the handler gets attached to this newly created thread. b. The thread is setup as a blocking looper thread. So this is not going to die.
now, we can 1. Send message on this handler. 2. Post runnable on this handler.
Both of them will be executed on the attached thread.
You have an option to either extend the Handler class and implement method handleMessage(Message msg). or you just provide implementation of the Handler.Callback in the constructor of the handler class. In either way the handleMessage(Messages msg) will be called on the attached thread.
To quit the thread you can send a specific type of message type, and upon receiving that message you'd just call Looper.myLooper().quit()
class LooperThread extends Thread { public Handler mHandler;
  public void run() {
      Looper.prepare();

      mHandler = new Handler() {
          public void handleMessage(Message msg) {
              // process incoming messages here
              if(msg.what == -1){
              Looper.myLooper().quit();
              }
          }
      };

      Looper.loop();
  }
}

Monday, September 8, 2014

Thread Life Cycle

We can prevent a thread from execution by using any of the 3 methods of Thread class:
  1. yield()
  2. join()
  3. sleep()
  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.Thread goes from running to runnable state after yield() is called and from there it again picked up by scheduler.
  2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.
  3. sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).Thread goes from running to sleep state after sleep() is called and from sleep state to runnable after sleep time is over.

Thursday, May 15, 2014

Android - Service vs Thread

If we need some background activities to go on only while application/Activity is active, a thread can do the required work.
If we need a component that keeps active even when, after a while, the Android system  decides to remove your Activities from memory, or application doesn't require user interaction for long, so there is no "Activities" with which user interacts then - Service should be the obvious choice, or even a "foreground service", which is considered even more important by the Android system and even less likely to be terminated to reclaim resources.
 A service is, of course, the way to go if you want to provide some service(s) to other applications, which can "bind" to a service only.

In Android, a Service does not provide any concurrent execution ("run in background"). It is actually more of a simple Java object which merely is instantiated (and managed) via the Android system instead of your application via new.
The most important property of a service is therefore not about deferring workload; this can be achieved with simple threads.
Service is part of Android system and it has the provision to also runs in the separate process and bind to the other application running in different processes.
Service always runs in the main thread of the application while thread runs on its own thread.
if you use an AsyncTask for a long-running process it may continue after you've navigated away from the Activity but:
  • If the Activity is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.
  • A background Activity is far more likely to be killed by Android when it needs memory than a Service.
All components of the same application usually run in the same process. When new component is started, it will  , by default, run in the same thread and inside the application main process unless you provide some thing else.  For example if you run a service by startService() method from an activity, this service runs in the main application process and thread. This is called “Single Thread Model”.

Sunday, March 9, 2014

All About Generics in Java

Java Generics Example

Generics was added in Java 5 to provide compile-time type checking and removing risk ofClassCastException that was common while working with collection classes. The whole collection framework was re-written to use generics for type-safety. Let’s see how generics help us using collection classes safely.
List list = new ArrayList(); list.add("abc"); list.add(new Integer(5)); //OK for(Object obj : list){ String str=(String) obj; //type casting leading //to ClassCastException at runtime }
Above code compiles fine but throws ClassCastException at runtime because we are trying to cast Object in the list to String whereas one of the element is of type Integer. After Java 5, we use collection classes like below.
List<String> list1 = new ArrayList<String>(); 
// java 7 ? List<String> list1 = new ArrayList<>(); list1.add("abc"); //list1.add(new Integer(5)); //compiler error for(String str : list1){ //no type casting needed, avoids ClassCastException }
Notice that at the time of list creation, we have specified that the type of elements in the list will be String. So if we try to add any other type of object in the list, the program will throw compile time error. Also notice that in for loop, we don’t need type casting of the element in the list, hence removing the ClassCastException at runtime.

Generics with Class and Interfaces

We can define our own classes and interfaces with generics type. A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter.
To understand the benefit, lets say we have a simple class as:
package com.amritesh.generics; public class GenericsTypeOld { private Object t; public Object get() { return t; } public void set(Object t) { this.t = t; } public static void main(String args[]){ GenericsTypeOld type = new GenericsTypeOld(); type.set("Amritesh"); String str = (String) type.get(); 
//type casting, error prone and can cause ClassCastException } }
Notice that while using this class, we have to use type casting and it can produce ClassCastException at runtime. Now we will use generics to rewrite the same class with generics type as shown below.
package com.amritesh.generics; public class GenericsType<T> {     private T t;         public T get(){        return this.t;    }         public void set(T t1){        this.t=t1;    }         public static void main(String args[]){        GenericsType<String> type = new GenericsType<>();        type.set("Amrit"); //valid                 GenericsType type1 = new GenericsType(); //raw type        type1.set("Pankaj"); //valid        type1.set(10); //valid and autoboxing support    }}
Notice the use of GenericsType class in the main method. We don’t need to do type-casting and we can remove ClassCastException at runtime. If we don’t provide the type at the time of creation, compiler will produce a warning that “GenericsType is a raw type. References to generic type GenericsType<T> should be parameterized”. When we don’t provide type, the type becomes Object and hence it’s allowing both String and Integer objects but we should always try to avoid this because we will have to use type casting while working on raw type that can produce runtime errors.
Tip: We can use @SuppressWarnings("rawtypes") annotation to suppress the compiler warning, check out java annotations tutorial.
Also notice that it supports java autoboxing.
Comparable interface is a great example of Generics in interfaces and it’s written as:
1
2
3
4
5
6
package java.lang;
import java.util.*;
public interface Comparable<T> {
    public int compareTo(T o);
}
In similar way, we can use generics in our interfaces and classes. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.

Generics Type Naming Convention

Naming convention helps us understanding code easily and having a naming convention is one of the best practices of java programming language. So generics also comes with it’s own naming conventions. Usually type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
  • E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
  • K – Key (Used in Map)
  • N – Number
  • T – Type
  • V – Value (Used in Map)
  • S,U,V etc. – 2nd, 3rd, 4th types

Generics in Methods and Constructors

Sometimes we don’t want whole class to be parameterized, in that case we can use generics type in methods also. Since constructor is a special kind of method, we can use generics type in constructors too.
Here is a class showing example of generics type in method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.amritesh.generics; public class GenericsMethods { //Generics in method public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){ return g1.get().equals(g2.get()); } public static void main(String args[]){ GenericsType<String> g1 = new GenericsType<>(); g1.set("Amritesh"); GenericsType<String> g2 = new GenericsType<>(); g2.set("Amritesh"); boolean isEqual = GenericsMethods.<String>isEqual(g1, g2); //above statement can be written simply as isEqual = GenericsMethods.isEqual(g1, g2); //This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. //Compiler will infer the type that is needed } }
Notice the isEqual method signature showing syntax to use generics type in methods. Also notice how to use these methods in our java program. We can specify type while calling these methods or we can invoke them like a normal method. Java compiler is smart enough to determine the type of variable to be used, this facility is called as type inference.

Generics Bounded Type Parameters

Suppose we want to restrict the type of objects that can be used in the parameterized type, for example in a method that compares two objects and we want to make sure that the accepted objects are Comparables. To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound, similar like below method.
1
2
3
public static <T extends Comparable<T>> int compare(T t1, T t2){
        return t1.compareTo(t2);
    }
The invocation of these methods is similar to unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error.
Bounded type parameters can be used with methods as well as classes and interfaces.
Generics supports multiple bounds also, i.e <T extends A & B & C>. In this case A can be an interface or class. If A is class then B and C should be interfaces. We can’t have more than one class in multiple bounds.

Generics and Inheritance

We know that Java inheritance allows us to assign a variable A to another variable B if A is subclass of B. So we might think that any generic type of A can be assigned to generic type of B, but it’s not the case. Lets see this with a simple program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.journaldev.generics; public class GenericsInheritance { public static void main(String[] args) { String str = "abc"; Object obj = new Object(); obj=str; // works because String is-a Object, inheritance in java MyClass<String> myClass1 = new MyClass<String>(); MyClass<Object> myClass2 = new MyClass<Object>(); //myClass2=myClass1; 
// compilation error since MyClass<String> is not a MyClass<Object> obj = myClass1; // MyClass<T> parent is Object } public static class MyClass<T>{} }
We are not allowed to assign MyClass<String> variable to MyClass<Object> variable because they are not related, in fact MyClass<T> parent is Object.

Generic Classes and Subtyping

We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
For example, ArrayList<E> implements List<E> that extends Collection<E>, so ArrayList<String> is a subtype of List<String> and List<String> is subtype of Collection<String>.
The subtyping relationship is preserved as long as we don’t change the type argument, below shows an example of multiple type parameters.
1
2
interface MyList<E,T> extends List<E>{
}
The subtypes of List<String> can be MyList<String,Object>, MyList<String,Integer> and so on.

Generics Wildcards

Question mark (?) is the wildcard in generics and represent an unknown type. The wildcard can be used as the type of a parameter, field, or local variable and sometimes as a return type. We can’t use wildcards while invoking a generic method or instantiating a generic class. In following sections, we will learn about upper bounded wildcards, lower bounded wildcards, and wildcard capture.

Generics Upper Bounded Wildcard

Upper bounded wildcards are used to relax the restriction on the type of variable in a method. Suppose we want to write a method that will return the sum of numbers in the list, so our implementation will be something like this.
1
2
3
4
5
6
7
public static double sum(List<Number> list){
        double sum = 0;
        for(Number n : list){
            sum += n.doubleValue();
        }
        return sum;
    }
Now the problem with above implementation is that it won’t work with List of Integers or Doubles because we know that List<Integer> and List<Double> are not related, this is when upper bounded wildcard is helpful. We use generics wildcard with extends keyword and the upper bound class or interface that will allow us to pass argument of upper bound or it’s subclasses types.
The above implementation can be modified like below program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.amritesh.generics; import java.util.ArrayList; import java.util.List; public class GenericsWildcards { public static void main(String[] args) { List<Integer> ints = new ArrayList<>(); ints.add(3); ints.add(5); ints.add(10); double sum = sum(ints); System.out.println("Sum of ints="+sum); } public static double sum(List<? extends Number> list){ double sum = 0; for(Number n : list){ sum += n.doubleValue(); } return sum; } }
It’s similar like writing our code in terms of interface, in above method we can use all the methods of upper bound class Number. Note that with upper bounded list, we are not allowed to add any object to the list except null. If we will try to add an element to the list inside the sum method, the program won’t compile.

Generics Unbounded Wildcard

Sometimes we have a situation where we want our generic method to be working with all types, in this case unbounded wildcard can be used. Its same as using <? extends Object>.
1
2
3
4
5
public static void printData(List<?> list){
        for(Object obj : list){
            System.out.print(obj + "::");
        }
    }
We can provide List<String> or List<Integer> or any other type of Object list argument to the printDatamethod. Similar to upper bound list, we are not allowed to add anything to the list.

Generics Lower bounded Wildcard

Suppose we want to add Integers to a list of integers in a method, we can keep the argument type as List<Integer> but it will be tied up with Integers whereas List<Number> and List<Object> can also hold integers, so we can use lower bound wildcard to achieve this. We use generics wildcard (?) with superkeyword and lower bound class to achieve this.
We can pass lower bound or any super type of lower bound as an argument in this case, java compiler allows to add lower bound object types to the list.
1
2
3
public static void addIntegers(List<? super Integer> list){
        list.add(new Integer(50));
    }

Sutyping using Generics Wildcard

1
2
List<? extends Integer> intList = new ArrayList<>(); List<? extends Number> numList = intList;  
// OK. List<? extends Integer> is a subtype of List<? extends Number>

Type Erasure

Generics was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.
For example if we have a generic class like below;
1
2
3
4
5
6
7
8
9
10
11
12
public class Test<T extends Comparable<T>> {
    private T data;
    private Test<T> next;
    public Test(T d, Test<T> n) {
        this.data = d;
        this.next = n;
    }
    public T getData() { return this.data; }
}
The Java compiler replaces the bounded type parameter T with the first bound interface, Comparable, as below code:
1
2
3
4
5
6
7
8
9
10
11
12
public class Test {
    private Comparable data;
    private Test next;
    public Node(Comparable d, Test n) {
        this.data = d;
        this.next = n;
    }
    public Comparable getData() { return data; }
}
Further Reading:
Generics doesn’t support sub-typing, so List<Number> numbers = new ArrayList<Integer>(); will not compile, learn why generics doesn’t support sub-typing.
We can’t create generic array, so List[] array = new ArrayList[10] will not compile, read why we can’t create generic array?.
Thats all for generics in java, generics is a really vast topic and requires a lot of time to understand and use it effectively. This post here is an attempt to provide basic details of generics and how can we use it to extend our program with type-safety.