performance #6 threading

217
Threading Britt Barak 14.9.16

Upload: vitali-pekelis

Post on 10-Feb-2017

74 views

Category:

Mobile


0 download

TRANSCRIPT

Page 1: Performance #6  threading

ThreadingBritt Barak

14.9.16

Page 2: Performance #6  threading

First,

Page 3: Performance #6  threading

Britt Barak

Britt Barak

@BrittBarak

● Figure 8 - Mobile Lead

● Android Academy TLV

Page 4: Performance #6  threading

Jonathan Yarkoni

Android Developer & Advocate Ironsource

Android Academy Staff

Yonatan LevinGoogle Developer

Expert & Android @ Gett

Britt BarakAndroid Lead

Figure8

Yossi SegevAndroid Developer

Crave

Page 6: Performance #6  threading

Upcoming Events

● Android Beginners - on 30/10 !

● Android UI / UX

● Community Hackathon

Page 7: Performance #6  threading

● Share your knowledge

● Give back to the community

● Grow professionally & personally

● Apply:

goo.gl/5qJ4nK

Mentors Program

Page 8: Performance #6  threading

….And Yourself?

Page 9: Performance #6  threading

- Threading primitives

- Dos & Don’ts

- Interacting with UI Thread

Threading- Async task- Loader- Handler thread- ThreadpoolExecut

or- Intent service- Services

performance- Threads priority- Thread-safe

methods

Page 10: Performance #6  threading

We Have A Winner!

SmoothMotion

60

No Difference

60+

Flip Book

12

Movies

Frames Per Second

Fluid Motion

24+effects

SmoothMotion

60

Page 11: Performance #6  threading

60 FPS

60 Frames / Second = Frame / 16.666 Millisecond

Page 12: Performance #6  threading

Who Does The Drawing?

Process

Main (/UI) Thread

Page 13: Performance #6  threading

What’s On The Main Thread?

Main Thread (UI Thread)

Process

System Event

Input Event Service Applicati

onUI Drawing

Page 14: Performance #6  threading

What’s On The Main Thread?

Main Thread (UI Thread)

Process

System Event

UI Drawing

UI Drawing

UI Drawing

UI Drawing

16ms

16ms

16ms

Animation

Page 15: Performance #6  threading

What’s On The Main Thread?

Main Thread (UI Thread)

Process

System Event

UI Drawing

Input Event

16ms

16ms

16ms

UI Drawing

UI Drawing

16ms

16ms

Page 16: Performance #6  threading

What’s On The Main Thread?

Main Thread (UI Thread)

Process

System Event

UI Drawing

Input Event

16ms

16ms

16ms

UI Drawing

UI Drawing

16ms

16ms

Dropped Frame

Page 17: Performance #6  threading

What Can We Do?

Page 18: Performance #6  threading

Ask For Help!

Process

Main (/UI) Thread

Page 19: Performance #6  threading

Ask For Help!

Process

Main (/UI) Thread

Worker Thread

Page 20: Performance #6  threading

So What’s The Catch?Only the UI thread can draw the UI !

Page 21: Performance #6  threading

Main Thread Rules:

1.Exclusive UI toolkit access2.Do not block it

Page 22: Performance #6  threading

So How To Offload A Task?

Page 23: Performance #6  threading

Java Thread WorkerThread

run ()thread.start()

MainThread

Page 24: Performance #6  threading

Java Thread WorkerThread

run ()thread.start()

MainThread

Page 25: Performance #6  threading

Examplethread = new CustomThread();//ORthread = new Thread (new CustomRunnable());

thread.start();

Page 26: Performance #6  threading

Examplepublic class CustomThread extends Thread { @Override public void run() {

doWorkInBackground(); }}public class CustomRunnable implements Runnable { @Override public void run() {

doWorkInBackground(); }}

Page 27: Performance #6  threading

Java Thread WorkerThread

run()

thread.start()

MainThread

?

Page 28: Performance #6  threading

ExampleActivity.runOnUiThread(runnable);//or

View.post(runnable);

More on that in a few slides...

Page 29: Performance #6  threading

Things can get ugly quite fast….

...any ideas?

Page 30: Performance #6  threading

How to offload task

●AsyncTask○Helps get work on/off the UI thread

●HandlerThread○Dedicated thread for API callbacks

●IntentService○Helps get intents off the UI thread

●ThreadPool○Running lots of parallel work

Page 31: Performance #6  threading

How to offload task

●AsyncTask○Helps get work on/off the UI thread

●HandlerThread○Dedicated thread for API callbacks

●IntentService○Helps get intents off the UI thread

●ThreadPool○Running lots of parallel work

Page 32: Performance #6  threading

AsyncTask

Page 33: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

Page 34: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onProgressUpdate ()

onPostExecute ()

publishProgress()

Page 35: Performance #6  threading

Examplepublic class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]);

publishProgress((int) ((i / (float) count) * 100)); } return totalSize; }

Page 36: Performance #6  threading

Example

public class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {// ...

protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);}

protected void onPostExecute(Long result) {showDialog("Downloaded " + result + " bytes");}

}

Page 37: Performance #6  threading

Example

DownloadFilesTask task = new DownloadFilesTask();

task.execute(URL1, URL2, URL3);

Page 38: Performance #6  threading

This Would Also WorkDownloadFilesTask task = new DownloadFilesTask(URL1, URL2, URL3);task.execute();

public class DownloadFilesTask extends AsyncTask<Void, Integer, Long> {private URL[] urls; public DownloadFilesTask(URL... urls) {

this.urls = urls;}…

}

Page 39: Performance #6  threading

Task Canceling

1.Set flag2.Invalidate Result3.Optionally - interruption

Page 40: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

Page 41: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute () cancel()

Page 42: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

onCancelled ()

cancel()

Page 43: Performance #6  threading

AsyncTask WorkerThread

doInBackground ()

onPreExecute ()

MainThread

onPostExecute ()

onCancelled ()

cancel()

while(! isCancelled()) {

// Do Work}

Page 44: Performance #6  threading

Example protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100));

// Escape early if cancel() is called if (isCancelled()) break; } return totalSize; }

@Override protected void onCancelled(Long result) { showDialog("Downloaded was cancelled after " + result + " bytes"); }

Page 45: Performance #6  threading

AsyncTask

●Single thread●Fit for short operations●Single time execution●Unaware of activity life cycle

Page 46: Performance #6  threading

Questions ?

Page 47: Performance #6  threading

Now, Imagine:

Page 48: Performance #6  threading

ExampleActivity

onCreate()

Page 49: Performance #6  threading

ExampleActivity AsyncTask A

onCreate()

doInBackground()

Page 50: Performance #6  threading

ExampleActivity AsyncTask A

onCreate()

doInBackground()

onDestroy()

onCreate()

Page 51: Performance #6  threading

ExampleActivity AsyncTask A

onCreate()

doInBackground()

onDestroy()

onCreate()

AsyncTask B

doInBackground()

Page 52: Performance #6  threading

Using AsyncTask - Problems

●Multiple running tasks●Irrelevant onPostExecute()●Un accessible objects●Longer to present results

Page 53: Performance #6  threading

Idea:●Coordinate task with UI life cycle

Page 54: Performance #6  threading

Idea:●Coordinate task with UI life cycle

Loader Pattern

Page 55: Performance #6  threading

Idea:●Coordinate task with UI life cycle

Loader Pattern30.10 -

New Course!Previous: goo.gl/rCIPRQ

Page 56: Performance #6  threading

Loader Pattern

LoaderHandles execution

Page 57: Performance #6  threading

Loader Pattern

LoaderCallbacksLoader

Handles results

Page 58: Performance #6  threading

Loader Pattern

LoaderCallbacks

LoaderManager

Loader

Manages loaders per lifecycle

Notifies callbacks

Page 59: Performance #6  threading

Loader Pattern

LoaderCallbacks

LoaderManager

Loader

manage

notify

manage,

notify

create

Page 60: Performance #6  threading

Loader Pattern : Loader● Abstract class that load data

asynchronously, and monitors its data source.

Loader

Callbacks

Manager

Loader

Page 61: Performance #6  threading

Loader Pattern : Loader● Abstract class that load data

asynchronously, and monitors its data source.

● Loader that uses AsyncTask

Loader

Async Task Loader

Callbacks

Manager

Loader

Page 62: Performance #6  threading

Loader Pattern : Loader● Abstract class that load data

asynchronously, and monitors its data source.

● Loader that uses AsyncTask

● AsyncTaskLoader that queries data from a ContentProvider and returns a Cursor.

Loader

Async Task Loader

Cursor Loader

Callbacks

Manager

Loader

Page 63: Performance #6  threading

Loader Pattern : LoaderCallbacks<D>

●onCreateLoader(int id, Bundle args)●onLoadFinished(Loader<D> loader, D data)●onLoaderReset(Loader<D> loader)

Callbacks

Manager

Loader

Page 64: Performance #6  threading

Loader Pattern : LoaderManager

●One per Activity / Fragment●Manages loaders (per user / lifecycle):

○ start / stop / reset loaders○ Retain state across config. changes○ Attach / detach callbacks○ Notify callbacks for results

Callbacks

Manager

Loader

Page 65: Performance #6  threading

How Does It Work?

Page 66: Performance #6  threading

How Does It Work?Activity

onCreate()

LoaderManagerinitLoad

er()

Page 67: Performance #6  threading

How Does It Work?Activity

onCreate()

LoaderManagerinitLoad

er()

LoaderCallbacks

AonCreate

Loader()

Page 68: Performance #6  threading

How Does It Work?Loader

loadInBackgroun

d()

Activity

onCreate()

LoaderManagerinitLoad

er()

LoaderCallbacks

AonCreate

Loader()

Page 69: Performance #6  threading

How Does It Work?Loader

loadInBackgroun

d()

Activity

onCreate()

LoaderManagerinitLoad

er()

LoaderCallbacks

A

onCreate()

initLoader()

onCreate

Loader()

Page 70: Performance #6  threading

How Does It Work?Loader

loadInBackgroun

d()

Activity

onCreate()

LoaderManagerinitLoad

er()

LoaderCallbacks

A

onCreate()

initLoader()

onCreate

Loader()

Page 71: Performance #6  threading

How Does It Work?Loader

loadInBackgroun

d()

Activity

onCreate()

onCreate()

LoaderManagerinitLoad

er()

initLoader()

LoaderCallbacks

AonCreate

Loader()

LoaderCallbacks

B

onLoadFinishes

()

Page 72: Performance #6  threading

So How Do We Use It ?

Page 73: Performance #6  threading

Recipe For Loaders

1. Unique loader ID2. Implement LoaderCallbacks<D>3. Init loader (with the ID)

Page 74: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

Page 75: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

ID

Page 76: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

onCreate

Loader()

ID

Page 77: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

onCreate

Loader()

Loader(ID,args)

ID

Page 78: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

ID

Page 79: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

oldLoader(ID, oldArgs)

old callback

s

ID

Page 80: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

oldLoader(ID, oldArgs)

args

ID

old callback

s

Page 81: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

oldLoader(ID, oldArgs)

old callbacks

old callback

scallback

s

ID

args

Page 82: Performance #6  threading

Recipe For Loaders : 3. Init Loader

initLoader(ID, args, callbacks)

oldLoader(ID, oldArgs)

old callbacksargs

old callback

scallback

s

ID

Switching the callbacks resolves configuration changes!

Page 83: Performance #6  threading

MainActivity.java@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_activity_with_loaders); resultView = (TextView)findViewById(R.id.with_loaderResult);

createTime = SystemClock.uptimeMillis(); resultView.setText("0");

getLoaderManager().initLoader(LOADER_ID, null, this);}

Page 84: Performance #6  threading

MainActivity.java@Overridepublic Loader<Long> onCreateLoader(int id, Bundle args) { return new DemoLoader(this);}

@Overridepublic void onLoadFinished(Loader<Long> loader, Long data) { long responseTime = data.longValue(); long delta = responseTime - createTime; resultView.setText(delta + "");}

@Overridepublic void onLoaderReset(Loader<Long> loader) { // Nothing to do}

Page 85: Performance #6  threading

DemoLoader.java@Overridepublic Long loadInBackground() { return TheBrain.upTimeInFiveSeconds();}

Page 86: Performance #6  threading

DemoLoader.java@Overrideprotected void onStartLoading() { if (mData != null) { deliverResult(mData); }

// TODO: register an observer

if (takeContentChanged() || mData == null) { forceLoad(); }}

Page 87: Performance #6  threading

DemoLoader.java@Overridepublic void deliverResult(Long data) { if (isReset()) { // The Loader has been reset; ignore the result and invalidate the data. releaseResources(data); return; } // Hold a reference to the old data so it doesn't get garbage collected. // We must protect it until the new data has been delivered. Long oldData = mData; mData = data; if (isStarted()) { // If the Loader is in a started state, deliver the results to the client. super.deliverResult(data); } // Invalidate the old data as we don't need it any more. if (oldData != null && oldData != data) { releaseResources(oldData); }}

Page 88: Performance #6  threading

Some Notes

Page 89: Performance #6  threading

InitLoader() - On Demand

public void onLoadButtonClick(View view) { isLoading = true; getLoaderManager().initLoader(LOADER_ID, null, this);}

Page 90: Performance #6  threading

InitLoader() - On Demand@Overrideprotected void onSaveInstanceState(Bundle outState) { outState.putBoolean(IS_LOADING, isLoading); super.onSaveInstanceState(outState);}

@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

if ((savedInstanceState != null) && savedInstanceState.getBoolean(IS_LOADING)){

getLoaderManager().initLoader(LOADER_ID, null, this);

}}

Page 91: Performance #6  threading

InitLoader() - Avoid Cache

public void onLoadButtonClick(View view) { isLoading = true; getLoaderManager().restartLoader(LOADER_ID, null, this);}

Page 92: Performance #6  threading

initLoader() VS. restartLoader()

initLoader(ID, args, callbacks)

onCreate

Loader()

Loader(id,args)

oldLoader(ID, oldArgs)

old callbacksargs

ID

old callback

scallback

s

Page 93: Performance #6  threading

initLoader() VS. restartLoader()

restartLoader(ID, args, callbacks)

onCreate

Loader()

Loader(id,args)

oldLoader(ID, oldArgs, oldCallbacks)

ID

Page 94: Performance #6  threading

initLoader() VS. restartLoader()

restartLoader(ID, args, callbacks)

onCreate

Loader()

Loader(id,args)

oldLoader(ID, oldArgs,

oldCallbacks)

ID

Page 95: Performance #6  threading

Any questions?

Page 96: Performance #6  threading

Now I have a question...

Page 97: Performance #6  threading

Example?

Camera.

open()

onPreviewFrame()

Page 98: Performance #6  threading

Which Thread?

- UI ?- AsyncTask ?- New Thread() ?

Page 99: Performance #6  threading

Let’s Take A Deeper Look

Page 100: Performance #6  threading

Reminder

Process

Main (/UI) Thread

Page 101: Performance #6  threading

A Deeper Look

Main Thread (UI Thread)

Process

System Event

Input Event Service Applicati

onUI Drawing

Page 102: Performance #6  threading

A Deeper Look

Main Thread (UI Thread)

Looper Message queue

Process

Page 103: Performance #6  threading

A Deeper Look

Main Thread (UI Thread)

Looper Message queue

HandlerHandle MSG

SendMSG

Process

Page 104: Performance #6  threading

A Deeper Look

Main Thread (UI Thread)Looper

Process

Handler Handle MSGSend MSG

Worker Thread

Page 105: Performance #6  threading

Example - ReminderActivity.runOnUiThread(runnable);//or

View.post(runnable);

Page 106: Performance #6  threading

But Also...handler.post();

handler.postAtFrontOfQueue();

handler.postDelayed();

handler.postAtTime();

Page 107: Performance #6  threading

This is called a HandlerThread

Page 108: Performance #6  threading

Why Am I Telling You This?

1.Better understand UI Thread2.Use for background work

Page 109: Performance #6  threading

ExampleHandlerTh

readCamera

.open()

onPreviewFrame()

Main Threadstart(

)

Page 111: Performance #6  threading

ExampleHandlerThread handlerThread = new HandlerThread(TAG);handlerThread.start();Handler handler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message msg) { Camera.open(); //..... }};

Page 112: Performance #6  threading

Don’t forget to quit!

handlerThread.quit() ●when you are done ● Or on activities onDestroy().

Page 113: Performance #6  threading

Questions ?

Page 114: Performance #6  threading

One more question:

Page 115: Performance #6  threading

Example

Intent

-?-

Hard work

Intent Hard work

Intent Hard work

Page 116: Performance #6  threading

Where?

- UI thread?- Async task?- HandlerThread?

Page 117: Performance #6  threading

Enters IntentService!

Page 118: Performance #6  threading

IntentService

- Extends Service- Handles intents on a HandlerThread- Stops when finishes

Page 119: Performance #6  threading

Service Benefits

- Alarms for repeated work - (refreshing, updating, logging analytics….)

- Less killable

Page 120: Performance #6  threading

Process Priority

https://developer.android.com/guide/components/processes-and-threads.html

M o r e K i l l a b l e

Foreground Activity

No Activity,Running Service

No Activity,No running Service

Page 121: Performance #6  threading

Be Aware:

- Work queue (potential blocking)

- One instance at a time

Page 122: Performance #6  threading

Should you extend Service yourself?

Page 123: Performance #6  threading

Service Performance

●Services cost time and memory.

○Creating, scheduling, running, and even destroying services

●Run on the UI thread

Page 124: Performance #6  threading

Make Sure You Need A Service

●Listen and respond to events ○BroadcastReceiver (even on background)

●Poll a server for data○FCM / GCM

●Work detached from UI○Use other primitive (saves scheduling)

Page 125: Performance #6  threading

Stopping

- stopSelf() or stopService()- On BoundService : unbindService() by all clients

Page 126: Performance #6  threading

Start & Bind Service

Start & stop & bind & unbind before the service terminates

Page 127: Performance #6  threading

Services Rules

●Avoid if possible

●Stop when possible

Page 128: Performance #6  threading

Questions ?

Page 129: Performance #6  threading

Last question:

Page 130: Performance #6  threading

Decoding 40 bitmaps, 4 millis each

Page 131: Performance #6  threading

Which Thread?

AsyncTask?IntentService? HandlerThread?

Page 132: Performance #6  threading

Observation

Linear - too long

Parallel - complicated

…………………..4ms 4ms 4ms 4ms

…...

4ms * 40 tasks =

160ms

4ms

4ms

Page 133: Performance #6  threading

Managing Threads

●Creation●Priorities●Work distribution●Destruction●Load balancing

Page 134: Performance #6  threading

ThreadPoolExecutor

Page 135: Performance #6  threading

So How Do We Use It ?

Page 136: Performance #6  threading

Recipe For ThreadPoolExecutor

1.Define class structure

2.Create ThreadPoolExecutor object3.Start a task

4.Return to UI thread

Page 137: Performance #6  threading

1.Define Class Structure

●Single control point ○restricted CPU or network resources.

●One per Runnable types

Page 138: Performance #6  threading

1.Define Class Structure

a.Single static instance b.Private constructor

Page 139: Performance #6  threading

1.Define Class Structure

public class PhotoManager {

static { //…

sInstance = new PhotoManager(); } private PhotoManager() { }}

Page 140: Performance #6  threading

2. Create ThreadPoolExecutor object

●Executors factory methods●Custome

Page 141: Performance #6  threading

Executors Factory Methods

●newCachedThreadPool() ●newFixedThreadPool(int) ●newSingleThreadExecutor()

Page 142: Performance #6  threading

Executors Factory Methods

●newCachedThreadPool(ThreadFactory) ●newFixedThreadPool(int, ThreadFactory) ●newSingleThreadExecutor(ThreadFactory)

Page 143: Performance #6  threading

Interface ThreadFactory

interface ThreadFactory {

Thread newThread(Runnable r);

}

Page 144: Performance #6  threading

Interface ThreadFactorypublic Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setPriority(this.threadPriority); thread.setName("Queue"); return thread;}

Page 145: Performance #6  threading

2. Create ThreadPoolExecutor object

●Executors factory methods●Custome

Page 146: Performance #6  threading

Determine the Thread Pool Parameters

●Initial size ●Maximum size●Keep alive time & unit●Tasks queue

Page 147: Performance #6  threading

Determine the Thread Pool Parameters

●Initial size

●Maximum size

●Keep alive time & unit●Tasks queue

Page 148: Performance #6  threading

How many threads should you create?

Page 149: Performance #6  threading

How many threads should you create?

can

Page 150: Performance #6  threading

How many threads should can you create?

- Software- Unlimited

- CPU- Limited

- Then, prioritize & schedule

Page 151: Performance #6  threading

How many threads should can you create?

●Cores available :Runtime.getRuntime().availableProcessors();

●Depends on system load●<= total #cores

Page 152: Performance #6  threading

Thread Priority

- CPU can only handle few at a time- Decides by priority- Default : as spawning thread

- Same priority = Same chance for resources

Page 153: Performance #6  threading

Thread Priority

android.os.Process.setThreadPriority()

Page 154: Performance #6  threading

Thread Priority

Page 155: Performance #6  threading

Thread Priority

- too high : may interrupt the UI thread / RenderThread

- too low : task may be too slow

Page 156: Performance #6  threading

Thread Priority

Yes, it might get exhausting…

...Some primitives do it for us (AsyncTask, IntentService)

Page 157: Performance #6  threading

How many threads should you create?

- Memory- Thread >= 64k

- Reuse!

- Trial & error - Systrace

Page 158: Performance #6  threading

Pool Size Notes

●corePoolSize == maximumPoolSize: ○fixed-size thread pool.

●maximumPoolSize == Integer.MAX_VALUE: ○an arbitrary number of concurrent tasks.

●Change dynamically : ○setCorePoolSize(int)

○setMaximumPoolSize(int).

Page 159: Performance #6  threading

Questions ?

Page 160: Performance #6  threading

Determine the Thread Pool Parameters

●Initial size ●Maximum size●Keep alive time & unit

●Tasks queue

Page 161: Performance #6  threading

Keep Alive Time & Unit

Thread idle duration before shutdown●setKeepAliveTime(long, TimeUnit)●Disable termination: Long.MAX_VALUE,

NANOSECONDS

Page 162: Performance #6  threading

Keep Alive Time & Unit●long keepAliveTime●TimeUnit unit

○DAYS○HOURS○MINUTES○SECONDS○MILLISECONDS○MICROSECONDS○NANOSECONDS

Page 163: Performance #6  threading

Determine the Thread Pool Parameters

●Initial size ●Maximum size●Keep alive time & unit●Tasks queue

Page 164: Performance #6  threading

Tasks Queue

●Runnables FIFO queue●Implements BlockingQueue interface.

Page 165: Performance #6  threading

Blocking Queue

Blocks when ●Trying to dequeue and is empty●Trying to enqueue and is full

Page 167: Performance #6  threading

Recipe For ThreadPool

1.Define class structure

2.Create ThreadPoolExecutor object3.Start a task

4.Return to UI thread

Page 168: Performance #6  threading

3. Start taskpublic class PhotoManager { ... static public PhotoTask startDownload(PhotoView imageView, boolean cacheFlag) { sInstance.mDownloadThreadPool.

execute(downloadTask.getDownloadRunnable()); }

Page 169: Performance #6  threading

TIP: Pre Start Threads

Threads start on execute().When constructing the pool with a non-empty queue, use: prestartCoreThread() or prestartAllCoreThreads()

Page 170: Performance #6  threading

Recipe For ThreadPool

1.Define class structure

2.Create ThreadPoolExecutor object3.Start a task

4.Return to UI thread

Page 171: Performance #6  threading

Back to UI thread

Page 172: Performance #6  threading

Back to UI thread

Thread

ManagerHandler

run()

ThreadPoolExecutor

Page 173: Performance #6  threading

Back to UI thread

ThreadTask Object

ManagerHandler

run()

ThreadPoolExecutor

setData&State()

Page 174: Performance #6  threading

Back to UI thread

ThreadTask Object

Manager

HandleState()Handler

run()

ThreadPoolExecutor

setData&State()

Page 175: Performance #6  threading

Back to UI thread

ThreadTask Object

Manager

HandleState()Handler

run()

handleMessage()

ThreadPoolExecutor

setData&State()

Page 176: Performance #6  threading

Runnable : Task → Set Data & Stateclass PhotoDecodeRunnable implements Runnable { PhotoDecodeRunnable(PhotoTask downloadTask) { mPhotoTask = downloadTask; }

byte[] imageBuffer = mPhotoTask.getByteBuffer(); ...

public void run() { returnBitmap = BitmapFactory.decodeByteArray(imageBuffer, 0,

imageBuffer.length, bitmapOptions); mPhotoTask.setImage(returnBitmap); mPhotoTask.handleState(DECODE_STATE_COMPLETED);

...

} ...}

Page 177: Performance #6  threading

Task : Manager → Handle Statepublic class PhotoTask { sPhotoManager = PhotoManager.getInstance();

public void handleState(int state) { int outState; switch(state) { case PhotoDecodeRunnable.DECODE_STATE_COMPLETED: outState = PhotoManager.TASK_COMPLETE; break; ... }

sPhotoManager.handleState(this, state); }}

Page 178: Performance #6  threading

Manager : Handler → Send Messagepublic class PhotoManager {

public void handleState(PhotoTask photoTask, int state) { switch (state) { case TASK_COMPLETE:

Message completeMessage = mHandler.obtainMessage(state,

photoTask); completeMessage.sendToTarget(); break; ... } ... }

Page 179: Performance #6  threading

Manager : Handler → Handle Message

private PhotoManager() {

mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message inputMessage) { PhotoTask photoTask = (PhotoTask) inputMessage.obj; PhotoView localView = photoTask.getPhotoView(); switch (inputMessage.what) { case TASK_COMPLETE:

localView.setImageBitmap(photoTask.getImage()); break; ... default: super.handleMessage(inputMessage); } } } }}

Page 180: Performance #6  threading

Questions ?

Page 181: Performance #6  threading

When to use?

Only for massive computing problems.

Page 182: Performance #6  threading

How to offload task

●AsyncTask○Helps get work on/off the UI thread

●HandlerThread○Dedicated thread for API callbacks

●IntentService○Helps get intents off the UI thread

●ThreadPool○Running lots of parallel work

Page 183: Performance #6  threading

Important Tips

Page 184: Performance #6  threading

1.Don’t Freeze !

AsyncTasks share same thread*...and so are IntentService’s Intents

AsyncTask Thread

AsyncTask#1 AsyncTask#2 AsyncTask#3 AsyncTask#

4

Page 185: Performance #6  threading

2. Don’t Leak!

Page 186: Performance #6  threading

What Is A Memory Leak ?

Reminder: Performance Course

#1 Lecture : Memory

goo.gl/QeGRP4

Page 187: Performance #6  threading

What Is A Memory Leak ?

Having a redundant reference in memory

Page 188: Performance #6  threading

What Is A Memory Leak ?

Every onCreate() → save a FAB reference

How many FABs would I have at the end?

Page 189: Performance #6  threading

A VIEW references its ACTIVITY,

which references its view HIERARCHY!

Page 190: Performance #6  threading

What Is A Memory Leak ?

Every onCreate() → save a FAB reference

How many activities would I have at the end?

Page 191: Performance #6  threading

Remember :

Task lifecycle is SEPARATE from the activity’s lifecycle !

Page 192: Performance #6  threading

2a. Don’t Leak - Implicit

Page 193: Performance #6  threading

Questions ?

Page 194: Performance #6  threading

2b. Don’t Leak - Explicitpublic class MainActivity extends Activity {

private class SomeTask extends AsyncTask<Object, Object, Object> {

@Override protected Object doInbackground(Object...

params) { doWorkInBackground(); }}

@Override protected void onCreate(Bundle savedInstanceState) {...}}

Page 195: Performance #6  threading

Inner non-static class references the outer

class !

Important !

Page 196: Performance #6  threading

2b. Don’t Leak - Explicit

Every onCreate() → create new task.

How many activities would I have at the end?

Page 197: Performance #6  threading

2b. Don’t Leak - Explicit

●Be parent class - Or -

●Be static class

Page 198: Performance #6  threading

If You Must...

●Use WeakReference<T> ●Access only on the main thread.

Page 199: Performance #6  threading

Avoid non-static inner classes private static class CountDownHandler extends Handler {

private final WeakReference<DialogCountdown> mDialogCountdownWeakReference;

public CountDownHandler(DialogCountdown dialogCountdown) { super(); mDialogCountdownWeakReference = new WeakReference<>(dialogCountdown); }

public void handleMessage(Message msg) { if(mDialogCountdownWeakReference.get()!=null) { mDialogCountdownWeakReference.get().onCountDown(); } } }

Page 200: Performance #6  threading

3. Don’t Cling

●Separate lifecycle from activity’s!●When back to UI thread, View can be:

○Removed

○Distroyed

○Change properties

●But task still runs and call callbacks

Page 201: Performance #6  threading

3. Don’t Cling

●Cancel tasks●Use callbacks / intents / events / … to return

results●Use correct primitive

Page 202: Performance #6  threading

Return Results

1.ResultReciever2.BroadcastReciever3.EventBus

Page 203: Performance #6  threading

Activity Service

ResultReceiver

startService( )

resultReceiver { onReceiveResult(){}}

Page 204: Performance #6  threading

Activity Service

ResultReceiver

ResultReceiver.send()startService( )

resultReceiver { onReceiveResult(){}}

Page 205: Performance #6  threading

ActivityResultReceiver resultReceiver =

new MyResultReceiver(handler);

MyService.start(this, resultReceiver);

Page 206: Performance #6  threading

MyResultReceiverprivate class MyResultReceiver extends ResultReceiver {//...

@Override protected void onReceiveResult

(int resultCode, Bundle resultData) {

handleResults(); }}

Page 207: Performance #6  threading

MyServicepublic static class MyService extends IntentService {

public static void start(Context context, ResultReceiver resultReceiver) { Intent intent = new Intent(context, MyService.class) .putExtra(KEY_RESULT_RECEIVER, resultReceiver); context.startService(intent);}

@Overrideprotected void onHandleIntent(Intent intent) { resultReceiver = intent.getParcelableExtra(KEY_RESULT_RECEIVER); //..... resultReceiver.send(Activity.RESULT_OK, data);

}}

Page 208: Performance #6  threading

Questions ?

Page 209: Performance #6  threading

Event Bus

Page 210: Performance #6  threading

Event Bus

Publisher:

bus.post(new AnswerAvailableEvent(42));

Subscriber:

@Subscribe

public void answerAvailable(AnswerAvailableEvent event) {

// TODO: React to the event somehow!

}

Page 211: Performance #6  threading

Event Bus

●http://square.github.io/otto/●http://greenrobot.org/eventbus

Page 212: Performance #6  threading

Questions ?

Page 213: Performance #6  threading

What Did We Have Today?

●AsyncTask○Helps get work on/off the UI thread

●Loader○Handle config. changes during background work

●HandlerThread○Dedicated thread for API callbacks

●IntentService○Helps get intents off the UI thread

●ThreadPool○Running lots of parallel work

Page 214: Performance #6  threading

What Did We Have Today?

● Services

● Threads priority

●Memory leaks

●Back to UI thread

Page 215: Performance #6  threading

Performance Course

#1. Memory

#2. GPU

#3. Layout

#4. Network

#5. Battery

#6. Threading

Page 216: Performance #6  threading

What’s Next?

● Android Beginners - on 30/10 !→ Android UI / UX → Community Hackathon

● Mentors Program - goo.gl/5qJ4nK

● Facebook Group - goo.gl/wBWxVF

Page 217: Performance #6  threading

Thank You !See you soon ;)