SlideShare a Scribd company logo
Efficient Android Threading
           Anders Göransson

      anders.goransson@jayway.com

            www.jayway.com
          www.jayway.com/blog
            www.oredev.org
Agenda

Optimize UI thread execution

       Threads on Android


     Asynchronous Techniques
Threads on Android


                         Android                     Linux
                          App                       Process

         UI


     Java Threads                  Native Threads


BG       BG         BG
Threads on Android

                   Android Scheduling
   Process level:
   1. Foreground


   2. Visible
                     Android
                      App
   3. Service


   4. Background
Threads on Android

                   Android Scheduling
                             Foreground Thread Group
   Process level:
                               App A
   1. Foreground                                       > 90%
                     App A
   2. Visible

                             Background Thread Group
   3. Service
                     App B     App B
   4. Background                                       < 10%
Threads on Android

                   Android Scheduling
                                                      Foreground Thread Group
   Process level:
                                                          App A
   1. Foreground                                                                              > 90%
                     App A
   2. Visible
                             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

                                                      Background Thread Group
   3. Service
                     App B                                App B
   4. Background                                                                              < 10%
Threads on Android

                                    Lifecycles
                                                       Threads
                     Linux
                    Process
                                           UI                BG
                                                      BG              BG


             Java Objects


         Activity         Service               Android Components

                                                Activity         Service

       Broadcast         Content
       Receiver          Provider           Broadcast            Content
                                            Receiver             Provider
Threads on Android

              Native Thread Lifecycle

                           Linux
                          Process

       UI

                           Process


      BG



            Application              Application   Time
              Start                  End
Threads on Android

              Example: Activity Lifecycle
   Activity
 Component
               onCreate()   onDestroy()   onCreate()        onDestroy()




   Activity
   Object
                 new()                                 GC

   Activity
   Object
                                           new()                      GC


                                                                           Time
Threads on Android

                 Example: Activity Lifecycle
     Activity
   Component
                  onCreate()           onDestroy()   onCreate()   onDestroy()




       BG
                               Start
Reference


      Activity
      Object
                    new()

      Activity
      Object
                                                      new()


                                                                                Time
Threads on Android

                Background Threads
   • A thread is a GC root

   • Implement cancellation policy for your
     background threads!
Use Cases

  UI                    BG               UI                    BG
Thread                 Thread          Thread                 Thread
         Get off the                            Get off the
         UI thread                              UI thread
           early!                                 early!




                         Do long                                Do long
                       running task                           running task



                                                  Report
                                                 result or
                                                update UI
Goal


What technique shall I use for
  my background thread
        execution?
Asynchronous Techniques
•   Thread
•   Executor
•   HandlerThread
•   AsyncTask
•   Service
•   IntentService
•   AsyncQueryHandler
•   Loader
Thread
• Plain old Java Thread
Thread

                           Creation and Start
                Anonymous Inner Class             External Class
  new Thread(new Runnable() {                Thread t = new MyThread();
              public void run() {            t.start();
                           // Do long task
              }
  }).start();



  Implicit reference to outer class
Thread

                   Pitfalls
  • Non-retained threads

  • Missing cancellation policy

  • Starting over and over again
Thread

                   Good Use Cases
  • One-shot tasks

         • Post messages to the UI thread at end.
One shot tasks


Thread
Executor
• Powerful task execution framework.
         public interface Executor {

                        public void execute(Runnable r);

         }




             Executor


             Executor
             Service


         ThreadPool
          Executor
Executor

                                       ExecutorService
Task submission:
 executorService.submit(MyTask);
 executorService.invokeAll(Collection<Tasks>);
 executorService.invokeAny(Collection<Tasks>);


Lifecycle management:
 executorService.shutdown();
 executorService.shutdownNow();


Lifecycle observation:
 executorService.isShutdown();
 executorService.isTerminated();
 executorService.awaitTermination();




                                                 shutdown()   Shutting   Terminate
                                  Running                                    d
                                                               Down
Executor

      Task / Execution Environment
Task:
Independent unit of work executed anywhere

  Runnable           Callable
      run()            call()
                                                        Task manager/observer:
                                                                        Future
                                                                        isDone()
                                                                      isCancelled()
                                                                         cancel()
                                             Future future = executorService.submit(Callable);

Execution Environment:
Technique used to execute the task

   Executor
 execute(Runnable)
Executor

               Thread Pools
   • Executor managing a pool of threads and
     a work queue.

   • Reduces overhead of thread creation
Executor

                            Thread Pools
Fixed Thread Pool    Executors.newFixedThreadPool(3)




Cached Thread Pool   Executors.newCachedThreadPool()




Single Thread Pool   Executors.newSingleThreadExecutor()




Custom Thread Pool   new ThreadPoolExecutor(corePoolSize, maximumPoolSize, aliveTime, unit, workQueue)
Executor

                   Pitfalls
   • Lost thread safety when switching from
     sequential to concurrent execution
Executor

               Good Use Cases
   • Execute tasks concurrently
      • Multiple Http requests
      • Concurrent image processing
      • Use cases gaining performance from
        concurrent execution.
   • Lifecycle management and observation of
     task execution.
   • Maximum platform utilization
Execution abstraction
                          Repetitive tasks
                          Concurrent execution
                          Sequential execution
         One shot tasks   Execution management
                          Task management

Thread                                       Executor
HandlerThread
• Inherits from Thread and encapsulates a
  Looper-object.
• Thread with a message queue and
  processing loop.
• Handles both Message and Runnable.


     t = new HandlerThread().start();             t.quit()
                                        Running              Dead
HandlerThread

                                     How it works
                                              Create and Start           Handler
                                          1                              Thread



                                      Message Queue
                               Add                              Process
                      3                                                       2




 1                                                  2
     t = new HandlerThread("BgThread");                 Handler h = new Handler(t.getLooper()) {
     t.start();                                                      @Override
                                                                     public void handleMessage(Message msg) {
                                                                                 //Process message
 3                                                                   }
     h.sendEmptyMessage(42);                            };
HandlerThread

                                       Handler
Runnable/Message submission:
 post(Runnable);
 postDelayed(Runnable);
 postAtTime(Runnable)
 postAtFrontOfQueue(Runnable);
 sendMessage(Message);
Lifecycle management:
 sendMessageDelayed(Message);
 sendMessageAtTime(Message);
 sendMessageAtFrontOfQueue(Message);




Runnable/Message removal:
 removeCallbacks(Runnable);
 removeMessages(Message)
HandlerThread

                Good Use Cases
  • Keep a thread alive

  • Sequential execution of messages
      • Avoid concurrent execution on multiple
        button clicks
      • State machine
      • Detailed control of message processing.
Execution abstraction
                                        Repetitive tasks
                                        Concurrent execution
                                        Sequential execution
             One shot tasks             Execution management
                                        Task management

Thread                                                          Executor

One shot tasks                                  Concurrent execution




                              “newSingleThreadExecutor”-alike
                              Execute Message and Runnable
                              Better clean up

                        Handler
                        Thread
AsyncTask
• Wraps Handler/Looper thread
  communication.
• Utilizes the Executor framework.
• Callbacks for UI operations and
  Background operation.
AsyncTask

                           How it works
                             UI                             BG
                           Thread                          Thread

     new AsyncTask.execute()
1
             onPreExecute()
2
                                            doInBackground()
                                        3


                                    AsyncTask.cancel()

             onCancelled()
             onPostExecute()
4b
4a
AsyncTask

                                       How it works
            public class MyActivity extends Activity {

                           public void onButtonClicked(View v) {
                                          new MyAsyncTask().execute("SomeInputString");
                           }
            }



            public class MyAsyncTask extends AsyncTask<String, Void, Integer> {

                           @Override
                           protected void onPreExecute() {
                           }

                           @Override
                           protected Integer doInBackground(String... params) {
                                          return null;
                           }

                           @Override
                           protected void onCancelled(Integer result) {
                           }

                           @Override
                           protected void onPostExecute(Integer result) {
                           }
            }
AsyncTask

                   Pitfalls
  • Application Global Behavior

  • execute()

  • Cancellation

  • Creation and Start
AsyncTask > Pitfalls

        Application Global Behavior

        Servic
          e        execute()

        Activity   execute()
                               Queue   Thread Pool
        Activity   execute()

        Receiver   execute()




           *       execute()
AsyncTask > Pitfalls

                                   execute()
              Execution behavior has changed over time


< Donut:           execute()


< Honeycomb: execute()


>= Honeycomb:
                       execute()


executeOnExecutor(Executor)
AsyncTask > Pitfalls

                                    execute()
        “So, if I call AsyncTask.execute on
      Honeycomb and later my tasks will run
                 sequentially, right?”



                       “Right?!?”


                                                 “Eh, it depends…”



             <uses-sdk android:targetSdkVersion="12" />

             <uses-sdk android:targetSdkVersion="13" />
AsyncTask > Pitfalls

                       Cancellation
   • Cancel AsyncTask when component
     finishes lifecycle.
       • Avoid UI updates on unavailable component.


   • cancel(true) == cancel(false) + interrupt()

   • Implement cancellation policy.
AsyncTask > Pitfalls

                       Creation and Start
   • at = new AsyncTask()
       • The first creation decides callback thread
           •   onPostExecute()
           •   onPublishProgress()
           •   onCancelled()


   • at.execute()
       • Callback thread of onPreExecute()
Execution abstraction
                                                   Repetitive tasks
                                                   Concurrent execution
                                                   Sequential execution
     One shot tasks
                                                   Execution management
                                                   Task management

              Thread                                                   Executor

                                                          Concurrent execution


                                                                           Task control

                                        “newSingleThreadExecutor”
AsyncTask<Void, Void, Void>             Execute Message and Runnable
AsyncTask.execute(Runnable)             Better clean up

                                   Handler
                                   Thread
                               Subsequent execution




                                 AsyncTask

                              One task with UI callback
Service
• Background execution on the UI thread

• Decouple background threads with other
  lifecycles, typically the Activity lifecycle.
Service

     Example: Lifecycle Decoupling
   Activity
 Component
              onCreate()            onDestroy()   onCreate()    onDestroy()




  Service
 Component
                       onCreate()                              onDestroy()




    BG




                                                                              Time
Service

              Good Use Cases
   • Tasks executed independently of user
     interaction.
   • Tasks executing over several Activity
     lifecycles or configuration changes.
Service

                   Pitfalls
   • Hidden AsyncTask.execute() with serial
     execution.
Execution abstraction
                                                   Repetitive tasks
                                                   Concurrent execution
                                                   Sequential execution
     One shot tasks
                                                   Execution management
                                                   Task management

              Thread                                                   Executor

                                                          Concurrent execution


                                                                           Task control

                                        “newSingleThreadExecutor”
AsyncTask<Void, Void, Void>             Execute Message and Runnable
AsyncTask.execute(Runnable)             Better clean up

                                   Handler
                                   Thread
                               Subsequent execution




                                 AsyncTask                                           Service
                                                                                 Activity lifecycle
                              One task with UI callback                          independent tasks
IntentService
• Service with a worker thread.

• On demand intents.

         public class MyIntentService extends IntentService {

                        @Override
                        protected void onHandleIntent(Intent intent) {
                        }

         }
IntentService

                                       Lifecycle


 IntentService
  Component
                 onCreate()                                onDestroy()




     BG               Intent 1   Intent 2   Intent 3   Intent n
                                                           stopSelf()




                                                                         Time
IntentService

                Good Use Cases
   • Serially executed tasks decoupled from
     other component lifecycles.

   • Off-load UI thread from
     BroadcastReceiver.

   • REST client (ResultReceiver as callback)
Execution abstraction
                                                   Repetitive tasks
                                                   Concurrent execution
                                                   Sequential execution
     One shot tasks
                                                   Execution management
                                                   Task management

              Thread                                                  Executor

                                                          Concurrent execution


                                                                           Task control

                                       “newSingleThreadExecutor”
AsyncTask<Void, Void, Void>            Execute Message and Runnable
AsyncTask.execute(Runnable)            Better clean up

                                   Handler
                                   Thread
                                Subsequent execution




                                                                                                             “On
                                                                                              “Continuous”
                                                                                                             demand”
                                                                                                                        Intent
                                 AsyncTask                                           Service
                                                                                                                       Service
                                                                                 Activity lifecycle
                              One task with UI callback                          independent tasks
AsyncQueryHandler
• API Level 1
• Asynchronous operations on a
  ContentResolver
  •   Query
  •   Insert
  •   Delete
  •   Update
• Wraps a HandlerThread
AsyncQueryHandler

                        How it works
                                  UI                            BG
                                Thread                         Thread

     new AsyncQueryHandler();
 1
     startQuery();
     startInsert();
     startUpdate();
     startDelete();
 2
                                                                  DB
                                                               operations

                                                                   3
                                         onQueryComplete();
                                         onInsertComplete();
                                         onUpdateComplete();
                                         onDeleteComplete();
AsyncQueryHandler

                    Cons
  • No cursor management
  • No content observation
  • No data retention on configuration
    changes
  • Background thread can’t be forced to quit
Execution abstraction
                                                   Repetitive tasks
                                                   Concurrent execution
                                                   Sequential execution                                         Asynchronous CRUD
     One shot tasks
                                                   Execution management
                                                   Task management                                                      Async
              Thread                                                  Executor                                          Query
                                                                                                                       Handler
                                                          Concurrent execution


                                                                           Task control

                                       “newSingleThreadExecutor”
AsyncTask<Void, Void, Void>            Execute Message and Runnable
AsyncTask.execute(Runnable)            Better clean up

                                   Handler
                                   Thread
                               Subsequent execution




                                                                                                             “On
                                                                                              “Continuous”
                                                                                                             demand”
                                                                                                                        Intent
                                 AsyncTask                                           Service
                                                                                                                       Service
                                                                                 Activity lifecycle
                              One task with UI callback                          independent tasks
Loader
•   API added in Honeycomb
•   Available in compatibility package
•   Load data in a background thread
•   Observes data changes
•   Retained on configuration changes
•   Connected to the Activity and Fragment
    lifecycles
Loader

                                   Basics
    3    Lifecycle management                   4     Retained on configuration change
                                   Loader




             1   Load data in BG            2       Observe data




                                    Data
                                   Source
Loader

              Data Sources


         Custom         Cursor
         Loader         Loader




         Any Data       Content
          Source        Provider
Loader

                                       How It Works
    public class AndroidLoaderActivity extends ListActivity implements LoaderCallbacks<Cursor>{

                  SimpleCursorAdapter mAdapter;

                  public void onCreate(Bundle savedInstanceState) {
                                 getLoaderManager().initLoader(0, null, this);
                  }

                  @Override
                  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                                return new CursorLoader(..., CONTENT_URI, ...);
                  }

                  @Override
                  public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
                                 mAdapter.swapCursor(c);
                  }

                  @Override
                  public void onLoaderReset(Loader<Cursor> arg0) {
                                 mAdapter.swapCursor(null);
                  }
    }
Loader

                         Pitfalls

    • Data loading will stop when
      Activity/Fragment is destroyed
         • Http requests not finished
Loader

              Good Use Cases

    • Loading data from Content Providers.
Execution abstraction
                                                   Repetitive tasks
                                                   Concurrent execution
                                                   Sequential execution                                         Asynchronous CRUD
     One shot tasks
                                                   Execution management
                                                   Task management                                                      Async
              Thread                                                   Executor                                         Query
                                                                                                                       Handler
                                                          Concurrent execution


                                                                           Task control                         Full CRUD

                                        “newSingleThreadExecutor”
AsyncTask<Void, Void, Void>             Execute Message and Runnable                                            Load data from CP
AsyncTask.execute(Runnable)             Better clean up                                                         Data observing
                                   Handler
                                                                                          Custom
                                   Thread
                                                                                          Loader
                                 Subsequent execution
                                                                                                                       Loader




                                                                                                             “On
                                                                                              “Continuous”
                                                                                                             demand”
                                                                                                                        Intent
                                 AsyncTask                                           Service
                                                                                                                       Service
                                                                                 Activity lifecycle
                              One task with UI callback                          independent tasks
Thank you for listening!
     Questions?

More Related Content

What's hot

User controls
User controlsUser controls
User controls
aspnet123
 
Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Python and its Applications
Python and its ApplicationsPython and its Applications
Python and its Applications
Abhijeet Singh
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
coolmirza143
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
myrajendra
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
malathip12
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
Hitesh-Java
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
Savvycom Savvycom
 
SQLite in Flutter.pptx
SQLite in Flutter.pptxSQLite in Flutter.pptx
SQLite in Flutter.pptx
Nabin Dhakal
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
Alexey Bovanenko
 
Python pandas Library
Python pandas LibraryPython pandas Library
Python pandas Library
Md. Sohag Miah
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
Abhilash M A
 
Migrating from MFC to Qt
Migrating from MFC to QtMigrating from MFC to Qt
Migrating from MFC to Qt
GlobalLogic Ukraine
 
Java Collections
Java  Collections Java  Collections
Fragment
Fragment Fragment
Aidl service
Aidl serviceAidl service
Aidl service
Anjan Debnath
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Android SDK Tutorial | Edureka
Android SDK Tutorial | EdurekaAndroid SDK Tutorial | Edureka
Android SDK Tutorial | Edureka
Edureka!
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 

What's hot (20)

User controls
User controlsUser controls
User controls
 
Android notification
Android notificationAndroid notification
Android notification
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Python and its Applications
Python and its ApplicationsPython and its Applications
Python and its Applications
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
SQLite in Flutter.pptx
SQLite in Flutter.pptxSQLite in Flutter.pptx
SQLite in Flutter.pptx
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
 
Python pandas Library
Python pandas LibraryPython pandas Library
Python pandas Library
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Migrating from MFC to Qt
Migrating from MFC to QtMigrating from MFC to Qt
Migrating from MFC to Qt
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Fragment
Fragment Fragment
Fragment
 
Aidl service
Aidl serviceAidl service
Aidl service
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Android SDK Tutorial | Edureka
Android SDK Tutorial | EdurekaAndroid SDK Tutorial | Edureka
Android SDK Tutorial | Edureka
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 

Similar to Efficient Android Threading

Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
Ruslan Novikov
 
Guides To Analyzing WebKit Performance
Guides To Analyzing WebKit PerformanceGuides To Analyzing WebKit Performance
Guides To Analyzing WebKit Performance
National Cheng Kung University
 
Applied Computer Science Concepts in Android
Applied Computer Science Concepts in AndroidApplied Computer Science Concepts in Android
Applied Computer Science Concepts in Android
National Cheng Kung University
 
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Mathias Seguy
 
Behavior Driven Development by Example
Behavior Driven Development by ExampleBehavior Driven Development by Example
Behavior Driven Development by Example
Nalin Goonawardana
 
Android101
Android101Android101
Android101
David Marques
 
Netflix conductor
Netflix conductorNetflix conductor
Netflix conductor
Viren Baraiya
 
Inside the android_application_framework
Inside the android_application_frameworkInside the android_application_framework
Inside the android_application_framework
surendray
 
Mono for android
Mono for androidMono for android
Mono for android
Willem Meints
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
James Williams
 
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
Daniel Bryant
 
Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_final
NAVER D2
 
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch
 
Node.JS briefly introduced
Node.JS briefly introducedNode.JS briefly introduced
Node.JS briefly introduced
Alexandre Lachèze
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
Lars Vogel
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
Andy Scherzinger
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
taher abdo
 
Improve Android System Component Performance
Improve Android System Component PerformanceImprove Android System Component Performance
Improve Android System Component Performance
National Cheng Kung University
 
Study of solution development methodology for small size projects.
Study of solution development methodology for small size projects.Study of solution development methodology for small size projects.
Study of solution development methodology for small size projects.
Joon ho Park
 
DSC NTUE Info Session
DSC NTUE Info SessionDSC NTUE Info Session
DSC NTUE Info Session
ssusera8eac9
 

Similar to Efficient Android Threading (20)

Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
 
Guides To Analyzing WebKit Performance
Guides To Analyzing WebKit PerformanceGuides To Analyzing WebKit Performance
Guides To Analyzing WebKit Performance
 
Applied Computer Science Concepts in Android
Applied Computer Science Concepts in AndroidApplied Computer Science Concepts in Android
Applied Computer Science Concepts in Android
 
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
 
Behavior Driven Development by Example
Behavior Driven Development by ExampleBehavior Driven Development by Example
Behavior Driven Development by Example
 
Android101
Android101Android101
Android101
 
Netflix conductor
Netflix conductorNetflix conductor
Netflix conductor
 
Inside the android_application_framework
Inside the android_application_frameworkInside the android_application_framework
Inside the android_application_framework
 
Mono for android
Mono for androidMono for android
Mono for android
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
 
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
 
Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_final
 
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
 
Node.JS briefly introduced
Node.JS briefly introducedNode.JS briefly introduced
Node.JS briefly introduced
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
 
Improve Android System Component Performance
Improve Android System Component PerformanceImprove Android System Component Performance
Improve Android System Component Performance
 
Study of solution development methodology for small size projects.
Study of solution development methodology for small size projects.Study of solution development methodology for small size projects.
Study of solution development methodology for small size projects.
 
DSC NTUE Info Session
DSC NTUE Info SessionDSC NTUE Info Session
DSC NTUE Info Session
 

Recently uploaded

CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
Claudio Di Ciccio
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
FODUU
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

Efficient Android Threading

  • 1. Efficient Android Threading Anders Göransson anders.goransson@jayway.com www.jayway.com www.jayway.com/blog www.oredev.org
  • 2. Agenda Optimize UI thread execution Threads on Android Asynchronous Techniques
  • 3. Threads on Android Android Linux App Process UI Java Threads Native Threads BG BG BG
  • 4. Threads on Android Android Scheduling Process level: 1. Foreground 2. Visible Android App 3. Service 4. Background
  • 5. Threads on Android Android Scheduling Foreground Thread Group Process level: App A 1. Foreground > 90% App A 2. Visible Background Thread Group 3. Service App B App B 4. Background < 10%
  • 6. Threads on Android Android Scheduling Foreground Thread Group Process level: App A 1. Foreground > 90% App A 2. Visible Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Background Thread Group 3. Service App B App B 4. Background < 10%
  • 7. Threads on Android Lifecycles Threads Linux Process UI BG BG BG Java Objects Activity Service Android Components Activity Service Broadcast Content Receiver Provider Broadcast Content Receiver Provider
  • 8. Threads on Android Native Thread Lifecycle Linux Process UI Process BG Application Application Time Start End
  • 9. Threads on Android Example: Activity Lifecycle Activity Component onCreate() onDestroy() onCreate() onDestroy() Activity Object new() GC Activity Object new() GC Time
  • 10. Threads on Android Example: Activity Lifecycle Activity Component onCreate() onDestroy() onCreate() onDestroy() BG Start Reference Activity Object new() Activity Object new() Time
  • 11. Threads on Android Background Threads • A thread is a GC root • Implement cancellation policy for your background threads!
  • 12. Use Cases UI BG UI BG Thread Thread Thread Thread Get off the Get off the UI thread UI thread early! early! Do long Do long running task running task Report result or update UI
  • 13. Goal What technique shall I use for my background thread execution?
  • 14. Asynchronous Techniques • Thread • Executor • HandlerThread • AsyncTask • Service • IntentService • AsyncQueryHandler • Loader
  • 15. Thread • Plain old Java Thread
  • 16. Thread Creation and Start Anonymous Inner Class External Class new Thread(new Runnable() { Thread t = new MyThread(); public void run() { t.start(); // Do long task } }).start(); Implicit reference to outer class
  • 17. Thread Pitfalls • Non-retained threads • Missing cancellation policy • Starting over and over again
  • 18. Thread Good Use Cases • One-shot tasks • Post messages to the UI thread at end.
  • 20. Executor • Powerful task execution framework. public interface Executor { public void execute(Runnable r); } Executor Executor Service ThreadPool Executor
  • 21. Executor ExecutorService Task submission: executorService.submit(MyTask); executorService.invokeAll(Collection<Tasks>); executorService.invokeAny(Collection<Tasks>); Lifecycle management: executorService.shutdown(); executorService.shutdownNow(); Lifecycle observation: executorService.isShutdown(); executorService.isTerminated(); executorService.awaitTermination(); shutdown() Shutting Terminate Running d Down
  • 22. Executor Task / Execution Environment Task: Independent unit of work executed anywhere Runnable Callable run() call() Task manager/observer: Future isDone() isCancelled() cancel() Future future = executorService.submit(Callable); Execution Environment: Technique used to execute the task Executor execute(Runnable)
  • 23. Executor Thread Pools • Executor managing a pool of threads and a work queue. • Reduces overhead of thread creation
  • 24. Executor Thread Pools Fixed Thread Pool Executors.newFixedThreadPool(3) Cached Thread Pool Executors.newCachedThreadPool() Single Thread Pool Executors.newSingleThreadExecutor() Custom Thread Pool new ThreadPoolExecutor(corePoolSize, maximumPoolSize, aliveTime, unit, workQueue)
  • 25. Executor Pitfalls • Lost thread safety when switching from sequential to concurrent execution
  • 26. Executor Good Use Cases • Execute tasks concurrently • Multiple Http requests • Concurrent image processing • Use cases gaining performance from concurrent execution. • Lifecycle management and observation of task execution. • Maximum platform utilization
  • 27. Execution abstraction Repetitive tasks Concurrent execution Sequential execution One shot tasks Execution management Task management Thread Executor
  • 28. HandlerThread • Inherits from Thread and encapsulates a Looper-object. • Thread with a message queue and processing loop. • Handles both Message and Runnable. t = new HandlerThread().start(); t.quit() Running Dead
  • 29. HandlerThread How it works Create and Start Handler 1 Thread Message Queue Add Process 3 2 1 2 t = new HandlerThread("BgThread"); Handler h = new Handler(t.getLooper()) { t.start(); @Override public void handleMessage(Message msg) { //Process message 3 } h.sendEmptyMessage(42); };
  • 30. HandlerThread Handler Runnable/Message submission: post(Runnable); postDelayed(Runnable); postAtTime(Runnable) postAtFrontOfQueue(Runnable); sendMessage(Message); Lifecycle management: sendMessageDelayed(Message); sendMessageAtTime(Message); sendMessageAtFrontOfQueue(Message); Runnable/Message removal: removeCallbacks(Runnable); removeMessages(Message)
  • 31. HandlerThread Good Use Cases • Keep a thread alive • Sequential execution of messages • Avoid concurrent execution on multiple button clicks • State machine • Detailed control of message processing.
  • 32. Execution abstraction Repetitive tasks Concurrent execution Sequential execution One shot tasks Execution management Task management Thread Executor One shot tasks Concurrent execution “newSingleThreadExecutor”-alike Execute Message and Runnable Better clean up Handler Thread
  • 33. AsyncTask • Wraps Handler/Looper thread communication. • Utilizes the Executor framework. • Callbacks for UI operations and Background operation.
  • 34. AsyncTask How it works UI BG Thread Thread new AsyncTask.execute() 1 onPreExecute() 2 doInBackground() 3 AsyncTask.cancel() onCancelled() onPostExecute() 4b 4a
  • 35. AsyncTask How it works public class MyActivity extends Activity { public void onButtonClicked(View v) { new MyAsyncTask().execute("SomeInputString"); } } public class MyAsyncTask extends AsyncTask<String, Void, Integer> { @Override protected void onPreExecute() { } @Override protected Integer doInBackground(String... params) { return null; } @Override protected void onCancelled(Integer result) { } @Override protected void onPostExecute(Integer result) { } }
  • 36. AsyncTask Pitfalls • Application Global Behavior • execute() • Cancellation • Creation and Start
  • 37. AsyncTask > Pitfalls Application Global Behavior Servic e execute() Activity execute() Queue Thread Pool Activity execute() Receiver execute() * execute()
  • 38. AsyncTask > Pitfalls execute() Execution behavior has changed over time < Donut: execute() < Honeycomb: execute() >= Honeycomb: execute() executeOnExecutor(Executor)
  • 39. AsyncTask > Pitfalls execute() “So, if I call AsyncTask.execute on Honeycomb and later my tasks will run sequentially, right?” “Right?!?” “Eh, it depends…” <uses-sdk android:targetSdkVersion="12" /> <uses-sdk android:targetSdkVersion="13" />
  • 40. AsyncTask > Pitfalls Cancellation • Cancel AsyncTask when component finishes lifecycle. • Avoid UI updates on unavailable component. • cancel(true) == cancel(false) + interrupt() • Implement cancellation policy.
  • 41. AsyncTask > Pitfalls Creation and Start • at = new AsyncTask() • The first creation decides callback thread • onPostExecute() • onPublishProgress() • onCancelled() • at.execute() • Callback thread of onPreExecute()
  • 42. Execution abstraction Repetitive tasks Concurrent execution Sequential execution One shot tasks Execution management Task management Thread Executor Concurrent execution Task control “newSingleThreadExecutor” AsyncTask<Void, Void, Void> Execute Message and Runnable AsyncTask.execute(Runnable) Better clean up Handler Thread Subsequent execution AsyncTask One task with UI callback
  • 43. Service • Background execution on the UI thread • Decouple background threads with other lifecycles, typically the Activity lifecycle.
  • 44. Service Example: Lifecycle Decoupling Activity Component onCreate() onDestroy() onCreate() onDestroy() Service Component onCreate() onDestroy() BG Time
  • 45. Service Good Use Cases • Tasks executed independently of user interaction. • Tasks executing over several Activity lifecycles or configuration changes.
  • 46. Service Pitfalls • Hidden AsyncTask.execute() with serial execution.
  • 47. Execution abstraction Repetitive tasks Concurrent execution Sequential execution One shot tasks Execution management Task management Thread Executor Concurrent execution Task control “newSingleThreadExecutor” AsyncTask<Void, Void, Void> Execute Message and Runnable AsyncTask.execute(Runnable) Better clean up Handler Thread Subsequent execution AsyncTask Service Activity lifecycle One task with UI callback independent tasks
  • 48. IntentService • Service with a worker thread. • On demand intents. public class MyIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } }
  • 49. IntentService Lifecycle IntentService Component onCreate() onDestroy() BG Intent 1 Intent 2 Intent 3 Intent n stopSelf() Time
  • 50. IntentService Good Use Cases • Serially executed tasks decoupled from other component lifecycles. • Off-load UI thread from BroadcastReceiver. • REST client (ResultReceiver as callback)
  • 51. Execution abstraction Repetitive tasks Concurrent execution Sequential execution One shot tasks Execution management Task management Thread Executor Concurrent execution Task control “newSingleThreadExecutor” AsyncTask<Void, Void, Void> Execute Message and Runnable AsyncTask.execute(Runnable) Better clean up Handler Thread Subsequent execution “On “Continuous” demand” Intent AsyncTask Service Service Activity lifecycle One task with UI callback independent tasks
  • 52. AsyncQueryHandler • API Level 1 • Asynchronous operations on a ContentResolver • Query • Insert • Delete • Update • Wraps a HandlerThread
  • 53. AsyncQueryHandler How it works UI BG Thread Thread new AsyncQueryHandler(); 1 startQuery(); startInsert(); startUpdate(); startDelete(); 2 DB operations 3 onQueryComplete(); onInsertComplete(); onUpdateComplete(); onDeleteComplete();
  • 54. AsyncQueryHandler Cons • No cursor management • No content observation • No data retention on configuration changes • Background thread can’t be forced to quit
  • 55. Execution abstraction Repetitive tasks Concurrent execution Sequential execution Asynchronous CRUD One shot tasks Execution management Task management Async Thread Executor Query Handler Concurrent execution Task control “newSingleThreadExecutor” AsyncTask<Void, Void, Void> Execute Message and Runnable AsyncTask.execute(Runnable) Better clean up Handler Thread Subsequent execution “On “Continuous” demand” Intent AsyncTask Service Service Activity lifecycle One task with UI callback independent tasks
  • 56. Loader • API added in Honeycomb • Available in compatibility package • Load data in a background thread • Observes data changes • Retained on configuration changes • Connected to the Activity and Fragment lifecycles
  • 57. Loader Basics 3 Lifecycle management 4 Retained on configuration change Loader 1 Load data in BG 2 Observe data Data Source
  • 58. Loader Data Sources Custom Cursor Loader Loader Any Data Content Source Provider
  • 59. Loader How It Works public class AndroidLoaderActivity extends ListActivity implements LoaderCallbacks<Cursor>{ SimpleCursorAdapter mAdapter; public void onCreate(Bundle savedInstanceState) { getLoaderManager().initLoader(0, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(..., CONTENT_URI, ...); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor c) { mAdapter.swapCursor(c); } @Override public void onLoaderReset(Loader<Cursor> arg0) { mAdapter.swapCursor(null); } }
  • 60. Loader Pitfalls • Data loading will stop when Activity/Fragment is destroyed • Http requests not finished
  • 61. Loader Good Use Cases • Loading data from Content Providers.
  • 62. Execution abstraction Repetitive tasks Concurrent execution Sequential execution Asynchronous CRUD One shot tasks Execution management Task management Async Thread Executor Query Handler Concurrent execution Task control Full CRUD “newSingleThreadExecutor” AsyncTask<Void, Void, Void> Execute Message and Runnable Load data from CP AsyncTask.execute(Runnable) Better clean up Data observing Handler Custom Thread Loader Subsequent execution Loader “On “Continuous” demand” Intent AsyncTask Service Service Activity lifecycle One task with UI callback independent tasks
  • 63. Thank you for listening! Questions?

Editor's Notes

  1. Android app has only UI thread from the startJava threads = Native Linux threads
  2. A Java Object goes through one Component lifecycle
  3. A Java Object goes through one Component lifecycle
  4. Compare different techniques to handle background execution.
  5. Future compatibility with more CPUs
  6. Future compatibility with more CPUs
  7. A Java Object goes through one Component lifecycle
  8. A Java Object goes through one Component lifecycle