Search This Blog

Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Tuesday, 17 December 2013

Handler vs Timer : fixed-period execution and fixed-rate execution android development

In Android Timer and Handler are both can be used for repetitive call. We can do same piece of task using either Timer or Handler (With runnable). First going to pros and cos of each we should look what documentation says about both. Its very important to avoid memory leak in android application

Timer Recurring tasks are scheduled with either a fixed period or a fixed rate:
  • With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.
   • With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.

Handler  

  • to schedule messages and runnables to be executed as some point in the future; and 
  • to enqueue an action to be performed on a different thread than your own.


Handler Implementation


  • How to create repetitive task using Handler

  Handler mHandler;
  public void useHandler() {
    mHandler = new Handler();
    mHandler.postDelayed(mRunnable, 1000);
  }

  private Runnable mRunnable = new Runnable() {

    @Override
    public void run() {
      Log.e("Handlers", "Calls");
      /** Do something **/
      mHandler.postDelayed(mRunnable, 1000);
    }
  };

  • How to remove pending execution from Handler

       mHandler.removeCallbacks(mRunnable);

  • How to schedule it again

      mHandler.postDelayed(mRunnable, 1000);


  • Where to perform Task

      Runnable works under UI thread so you can update UserInterface in Handler respective Runnable


Timer Implementation


  • How to create repetitive task using Timer

  public void useTimer() {
    Timer mTimer = new Timer();
    mTimer.cancel();
    mTimer.schedule(new TimerTask() {

      @Override
      public void run() {
        Log.e("Timer", "Calls");
      }
    }, 1000, 1000);
  }


  • How to remove pending execution from Timer

      mTimer.cancel(); will cancel all the schedule task.

  • How to schedule it again

        You can not reschedule Timer again. So you to create object of timer again if you are trying to reschedule its task.


Comparison Handler VS Timer


  • While rescheduling Handler is very easy, you can not reschedule Timer


  • In Handler you can attach to any Runnable but Timer schedule for only one TimerTask


  • TimerTask is purely background task so you can not update UserInterface, but that's not true for Handler's Runnables
Timer Cause Execption


  • Timer tends to leak more memory compare to Handler see the graph of object retains by timer and Handler. It will increase rapidly for Timer if you are creating and scheduling new task.

Handler Memory Graph

Timer Memory Graph
Which one to use Obviously i will recommend to use Handler with Runnable

Thursday, 8 November 2012

why two way exist to implement thread in java ?

Java has great concept called Thread. Thread is most discussed and assume to be most difficult  concept by people. while creating a simple thread, Java provide two ways

1) Extends Thread class 

public class Method1 extends Thread {

 public static void main(String[] args) {
  Method1 tm = new Method1();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  super.run();
  System.out.println("Extends Thread to create a Thread :)");
 }
}

2) Implement Runnable interface

public class Method2 implements Runnable {

 public static void main(String[] args) {
  Method2 tm = new Method2();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  System.out.print("Implement Runnable interface to create a Thread");
 }
}

So doubt goes increasing for a new programmer. Two ways to doing same thing ? why these necessity exists Let them clarify

Noted : Java provide inheritance . So we can use on class property inside another class by extending class. Consider class MN has method addSum(), iNeedMn want to use this addSum() then simple iNeedMn extends MN is solution. This is called single inheritance

    public class MN{
       
        public void addSum(){
            System.out.print("From MN");
        }
    }
   
    public class iNeedMn extends MN{
        @Override
        public void addSum() {
            super.addSum();
        }
    }

Consider now iNeedMn want to access the property of Thread class also (So called multiple Inheritance(is not allowed in JAVA) i.e one class can extends any number of class) or say iNeedMn need to be use as Thread somewhere. Impossible ???

Cause of providing two to make a thread is to avoid impact of banned multiple inheritance.We can not extends two classes but we can implement any number of interface

Which way to prefer ?

Implementing Runnable is preferred way.It's generally discouraged to extend the Thread class. The Thread class has a lot of overhead and the Runnable interface doesn't   

Saturday, 21 April 2012

Thread Synchronization in Java and Android

Java is always fun love for me. Thread was the only thing that make feared so study it hard and now want to make sure that it will not happen with any one now. I have discussed about how to create simple Thread. But most important is to Synchronization of two thread.

For example -We have one file. And we have two thread one for reading this file and second for writing file. So in this case if we want to read everything that has to be written by write thread.Then Read thread to wait (if write is running) until Write does not complete it task.

For Thread Synchronization important thing is to note that we can synchronize only on one object.
Although i will write code in android technology but in java and Blackberry its almost same.For this i need to take two thread

Thread 1

private class Thread2 extends Thread{
        
        private SynDemo d;
        public Thread2(SynDemo sDemo) {
            d=sDemo;
        }
        @Override
        public void run() {
            super.run();
            d.printNumber("Thread2");
        }
    }                                                                           

This Thread will print number from 0 to 2000.Next thread also will doing the same.

Thread 2

Thursday, 19 April 2012

Simple Thread example in java

Before posting this example i would to thank Herbert Shield


The simple example shown in full on the previous page defines two classes: SimpleThread and TwoThreadsTest. Let's begin our exploration of the application with the SimpleThread class: a subclass of the Thread class that is provided by the java.lang package.
class SimpleThread extends Thread {
    public SimpleThread(String str) {
 super(str);
    }
    public void run() {
 for (int i = 0; i < 10; i++) {
     System.out.println(i + " " + getName());
            try {
  sleep((int)(Math.random() * 1000));
     } catch (InterruptedException e) {}
 }
 System.out.println("DONE! " + getName());
    }
}
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is only interesting to us because it sets the Thread's name which is used later in the program.
The next method in the SimpleThread class is the run() method. The run() method is the heart of any Thread--it's where the action of the Thread takes place. The run() method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread then sleeps for a random interval between 0 and 1 second. After the loop has finished, the run() method prints "DONE!" along with the name of the thread. That's it for the SimpleThread class.
The TwoThreadsTest class provides a main() method that creates two SimpleThread threads: one is named "Jamaica" and the other is named "Fiji". (If you can't decide on where to go for vacation you can use this program to help you decide--go to the island whose thread prints "DONE!" first.)
class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}
Android News and source code