SlideShare une entreprise Scribd logo
1  sur  19
Async Task, Threads, Pools,
and ExecutorsOh My!
Stacy Devino
@ 360AnDev 2016
STACY DEVINO
• Senior Android Innovator at The Home Depot Dallas
Technology Center
• Works on Consumer Mobile App and Internal
Product Innovation
• Six Sigma BlackBelt, Intel Innovator, DMS Member,
Vintage game collector/restorer
• Women Techmakers Lead for Dallas/ Ft. Worth
WEBSITES
www.stacydevino.com
www.ledgoes.com
www.openbrite.com
EMAIL
childofthehorn@gmail.com
G+
https://plus.google.com/+S
tacyDevino
TWITTER
@DoesitPew
Why do I need to know Multithreaded Programming?
What is it?
Basically, it allows you to
run multiple tasks
concurrently (all at the same
time) without interfering with
each other.
Important : CORE SKILL of the modern developer
What is a
Thread?
Thread is an independent
execution worker.
All of Android works on
Threads.
Generally, the Main Thread
is your UI Thread in
Android (ex “Hello World”
app).
Required for things such
as Login, pre-loading, and
Web/RESTful APIs
String != Bunch of Threads
Android has 4 basic types of Threads
Thread (Java Standard)
Handler (Android Type)
AsyncTask (Android Only)
HandlerThread (Android
Only, Handler/Looper combo)
Other stuff we will
not be going through:
Futures
IntentService
Jobs / Alarms
Basic Thread
What does this do?
Compute a new Random value
to be used based off of a
seed value.
How is this useful?
If you compute big Random
values on big Seeds, this
could take many processor
cycles.
long rootRandom =
System.currentMillis();
private class RandomThread
extends Thread {
long seed;
RandomThread (long seed){
this.seed = seed;
}
@Override
public void run() {
Random seededRandom =
new
Random (seed);
rootRandom =
seededRandom.nextInt();
}
}
Delayed Tasks
with Handler
Can be called/used
anywhere, ex. Services or
external classes
Allows direct
communication with UI/Main
Thread, good with
Messaging Tasks.
private Handler mHandler = new Handler();
private int lifeSignDelay = 5000;
private Runnable mainRunnable = new Runnable()
{
@Override
public void run() {
sendLifeSign(true);
mHandler.postDelayed(
mainRunnable, lifeSignDelay);
}
}
Async Task
Can ONLY be called from an
Activity (main thread,boo)
Simplified Interface for
Task based objects
Good for User Logins /
pre-loading data to be
shown on the UI
public class MyUIActivity extends AppCompatActivity {
// ……..
private ImageView = view.findViewById(R.id.someView)
// OnCreate and all other tasks contained above
//Usage
// … inside of a function or from onClick
new DownloadImageTask()
.execute("http://example.com/image.png");
//Async Task
private class DownloadImageTask extends
AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
}
HandlerThread
(Handler + Looper)
It’s a Thread with an
Embedded Looper instance,
keeps it alive and going
handling messages/queue.
Basic
HandlerThread handlerThread = new
HandlerThread("newHandlerThread");
handlerThread.start();
Handler myHandler = new Handler(handlerThread.getLooper());
myHandler.post(new Runnable(){…});
Fancy
private void newOpenCamera() {
if (mThread == null) {
mThread = new CameraHandlerThread();
}
synchronized (mThread) {
mThread.openCamera();
}
}
private CameraHandlerThread mThread = null;
private class CameraHandlerThread extends HandlerThread {
Handler mHandler = null;
CameraHandlerThread() {
super("CameraHandlerThread");
start();
mHandler = new Handler(getLooper());
}
void openCamera() {
mHandler.post(new Runnable() {
@Override
public void run() {
oldOpenCamera();//backup
}
});
}
}
Lambda Expressions (only in Java 8)
private class RandomThread
extends Thread {
long seed;
RandomThread (long seed){
this.seed = seed;
}
@Override
public void run() {
Random seededRandom =
new Random
(seed);
rootRandom =
seededRandom.nextInt();
}
}
private Runnable RandomThread
= (long seed) -> {
Random seededRandom =
new Random
(seed);
rootRandom =
seededRandom.nextInt();
}
becomes
Advanced Threads
and
Thread
Management
Self Managed
Thread
Can be Runnables or Thread
Closes itself
Can Spawn new Threads
Example shows linked
threads of a simple
Socket-level communication
app
class ConnectThread implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (newConnection) {
newConnection = false;
SocketClass.startClient();
new Thread(new TimeOutThread()).start();
}
if (serverReply != null) {
if(
serverReply.equals(Constants.ACK)
||serverReply.equals(Constants.NAK)
||serverReply.equals(Constants.STOP)
{
Thread.currentThread().interrupt();
sendCompleteEvent(serverReply);
return;
}
}
}
}
}
Executors
It’s Super Effective!
Executes Runnable Tasks
Asynchronous or Sequential
New Thread Spawner
(new Thread(RunnableTask)).start();
becomes
Executor executor = anExecutor();
executor.execute(new RunnableTask());
executor.execute(new NextRunnableTask());
Direct Call in Same Thread
class DirectExecutor implements Executor {
public void execute(Runnable task) {
task.run();
}
}
Asynchronous Call in new Thread
class ThreadPerTaskExecutor implements
Executor {
public void execute(Runnable task) {
new Thread(task).start();
}
}
ThreadPool
Executor
Executor which works with a
group of maintained “Worker”
threads.
Threads themselves do not
die, but merely transform.
Create the Pool
ThreadPoolExecutor mThreadPool =
new ThreadPoolExecutor(
// Initial processor pool size
Runtime.getRuntime().availableProcessors(),
// Max processor pool size
Runtime.getRuntime().availableProcessors(),
//Time to Keep Alive
3,
//TimeUnit for Keep Alive
TimeUnit.SECONDS,
//Queue of Runnables
mWorkQueue
);
Using the Pool
public class MyTaskManager {
//…..
// Run the Task on the Pool
mThreadPool.execute(
someTask.getRunnable());
//.. Now when done
mThreadPool.shutdown();
}
Executor
Services
Control of task that
provide Futures (look at
this elsewhere) in a
single Entity.
Examples:
ScheuduledExecutorService
private class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
//Run on the new ThreadPool
pool.execute(
new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
//This signals shutdown the pool
pool.shutdown();
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) { this.socket = socket; }
public void run() {
// read and service request on socket
}
}
* from developer.android.com
RXJava and libraries
that have their own
Thread Management
aka RXAndroid
Advantages:
Significantly simplifies writing of
modules as 3-4 threads can be
combined in a single Observable.
Very easy to set up communication
between multiple “Threads” or
RXJava components.
Pools and maintains worker threads.
Easy to serialize thread results
and information.
Disadvantages:
If not used properly, can have
leaked messages and observables.
(especially in the hands of those
who don’t know thread management).
It's not always as perfect in
management as a specialty built
component.
Event and Task based, so self
propagating processes are more work
to set up.
Other Examples of Self Managing Libs
RetroFit : Turns Restful API
calls into Java interfaces.
Handles all Thread management
and parsing. (by ReactiveX, many
contributions by Square... Lots
of Jake Wharton)
Bolts-Android : Task based model
which works on the premise of
Promises (Javascript). Allows
easy chaining of Asynchronous
tasks. (by Parse and Facebook)
Picasso : Image Loader that
uses ThreadPoolExecutor to
preload and size images. (by
Square)
Image Loader uses
ThreadPoolExecutor and Handlers
to preload and resize images.
(by Bumptech)
Thanks!

Contenu connexe

Tendances

Tendances (20)

Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Internal Android Library Management (DroidCon SF 2016, Droidcon Italy 2016)
Internal Android Library Management (DroidCon SF 2016, Droidcon Italy 2016)Internal Android Library Management (DroidCon SF 2016, Droidcon Italy 2016)
Internal Android Library Management (DroidCon SF 2016, Droidcon Italy 2016)
 
GWT Introduction and Overview - SV Code Camp 09
GWT Introduction and Overview - SV Code Camp 09GWT Introduction and Overview - SV Code Camp 09
GWT Introduction and Overview - SV Code Camp 09
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Aug penguin16
Aug penguin16Aug penguin16
Aug penguin16
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with Swift
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
 
DJango
DJangoDJango
DJango
 

En vedette

Java Micro Edition Platform & Android - Seminar on Small and Mobile Devices
Java Micro Edition Platform & Android - Seminar on Small and Mobile DevicesJava Micro Edition Platform & Android - Seminar on Small and Mobile Devices
Java Micro Edition Platform & Android - Seminar on Small and Mobile Devices
juricde
 

En vedette (20)

GKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testingGKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testing
 
RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android Looper
 
Java Micro Edition Platform & Android - Seminar on Small and Mobile Devices
Java Micro Edition Platform & Android - Seminar on Small and Mobile DevicesJava Micro Edition Platform & Android - Seminar on Small and Mobile Devices
Java Micro Edition Platform & Android - Seminar on Small and Mobile Devices
 
Intro to Android : Making your first App!
Intro to Android : Making your first App!Intro to Android : Making your first App!
Intro to Android : Making your first App!
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
 
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법
 
디자이너 없어도 괜찮아! (feat.Material Design Guide)
디자이너 없어도 괜찮아! (feat.Material Design Guide)디자이너 없어도 괜찮아! (feat.Material Design Guide)
디자이너 없어도 괜찮아! (feat.Material Design Guide)
 
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
GKAC 2014 Nov. - RxJava를 활용한 Functional Reactive Programming
GKAC 2014 Nov. - RxJava를 활용한 Functional Reactive ProgrammingGKAC 2014 Nov. - RxJava를 활용한 Functional Reactive Programming
GKAC 2014 Nov. - RxJava를 활용한 Functional Reactive Programming
 
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media Playback
 
FIrebase를 이용한 호우호우 미니게임 만들기
FIrebase를 이용한 호우호우 미니게임 만들기FIrebase를 이용한 호우호우 미니게임 만들기
FIrebase를 이용한 호우호우 미니게임 만들기
 
Reinfocement learning
Reinfocement learningReinfocement learning
Reinfocement learning
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
Introduce Android TV and new features from Google I/O 2016
Introduce Android TV and new features from Google I/O 2016Introduce Android TV and new features from Google I/O 2016
Introduce Android TV and new features from Google I/O 2016
 
Tomcat Optimisation & Performance Tuning
Tomcat Optimisation & Performance TuningTomcat Optimisation & Performance Tuning
Tomcat Optimisation & Performance Tuning
 
Android - Preventing common memory leaks
Android - Preventing common memory leaksAndroid - Preventing common memory leaks
Android - Preventing common memory leaks
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 

Similaire à Async task, threads, pools, and executors oh my!

Introduction to nodejs
Introduction to nodejsIntroduction to nodejs
Introduction to nodejs
James Carr
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mohammad Shaker
 

Similaire à Async task, threads, pools, and executors oh my! (20)

Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threading
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adapters
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
Introduction to nodejs
Introduction to nodejsIntroduction to nodejs
Introduction to nodejs
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Node
NodeNode
Node
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
 

Plus de Stacy Devino

Plus de Stacy Devino (6)

IoT with Firebase : IoT DevFest Phoenix 2018
IoT with Firebase : IoT DevFest Phoenix 2018IoT with Firebase : IoT DevFest Phoenix 2018
IoT with Firebase : IoT DevFest Phoenix 2018
 
Beautiful text spread your wings with Spannables
Beautiful text   spread your wings with SpannablesBeautiful text   spread your wings with Spannables
Beautiful text spread your wings with Spannables
 
Big Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improvedBig Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improved
 
Big Trouble in Little Networks
Big Trouble in Little Networks Big Trouble in Little Networks
Big Trouble in Little Networks
 
WWC 3D printing basics with stacy devino
WWC 3D printing basics with stacy devinoWWC 3D printing basics with stacy devino
WWC 3D printing basics with stacy devino
 
Timings of Init : Android Ramdisks for the Practical Hacker
Timings of Init : Android Ramdisks for the Practical HackerTimings of Init : Android Ramdisks for the Practical Hacker
Timings of Init : Android Ramdisks for the Practical Hacker
 

Dernier

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 

Dernier (20)

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 

Async task, threads, pools, and executors oh my!

  • 1. Async Task, Threads, Pools, and ExecutorsOh My! Stacy Devino @ 360AnDev 2016
  • 2. STACY DEVINO • Senior Android Innovator at The Home Depot Dallas Technology Center • Works on Consumer Mobile App and Internal Product Innovation • Six Sigma BlackBelt, Intel Innovator, DMS Member, Vintage game collector/restorer • Women Techmakers Lead for Dallas/ Ft. Worth WEBSITES www.stacydevino.com www.ledgoes.com www.openbrite.com EMAIL childofthehorn@gmail.com G+ https://plus.google.com/+S tacyDevino TWITTER @DoesitPew
  • 3. Why do I need to know Multithreaded Programming? What is it? Basically, it allows you to run multiple tasks concurrently (all at the same time) without interfering with each other. Important : CORE SKILL of the modern developer
  • 4. What is a Thread? Thread is an independent execution worker. All of Android works on Threads. Generally, the Main Thread is your UI Thread in Android (ex “Hello World” app). Required for things such as Login, pre-loading, and Web/RESTful APIs String != Bunch of Threads
  • 5. Android has 4 basic types of Threads Thread (Java Standard) Handler (Android Type) AsyncTask (Android Only) HandlerThread (Android Only, Handler/Looper combo) Other stuff we will not be going through: Futures IntentService Jobs / Alarms
  • 6. Basic Thread What does this do? Compute a new Random value to be used based off of a seed value. How is this useful? If you compute big Random values on big Seeds, this could take many processor cycles. long rootRandom = System.currentMillis(); private class RandomThread extends Thread { long seed; RandomThread (long seed){ this.seed = seed; } @Override public void run() { Random seededRandom = new Random (seed); rootRandom = seededRandom.nextInt(); } }
  • 7. Delayed Tasks with Handler Can be called/used anywhere, ex. Services or external classes Allows direct communication with UI/Main Thread, good with Messaging Tasks. private Handler mHandler = new Handler(); private int lifeSignDelay = 5000; private Runnable mainRunnable = new Runnable() { @Override public void run() { sendLifeSign(true); mHandler.postDelayed( mainRunnable, lifeSignDelay); } }
  • 8. Async Task Can ONLY be called from an Activity (main thread,boo) Simplified Interface for Task based objects Good for User Logins / pre-loading data to be shown on the UI public class MyUIActivity extends AppCompatActivity { // …….. private ImageView = view.findViewById(R.id.someView) // OnCreate and all other tasks contained above //Usage // … inside of a function or from onClick new DownloadImageTask() .execute("http://example.com/image.png"); //Async Task private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } } }
  • 9. HandlerThread (Handler + Looper) It’s a Thread with an Embedded Looper instance, keeps it alive and going handling messages/queue. Basic HandlerThread handlerThread = new HandlerThread("newHandlerThread"); handlerThread.start(); Handler myHandler = new Handler(handlerThread.getLooper()); myHandler.post(new Runnable(){…}); Fancy private void newOpenCamera() { if (mThread == null) { mThread = new CameraHandlerThread(); } synchronized (mThread) { mThread.openCamera(); } } private CameraHandlerThread mThread = null; private class CameraHandlerThread extends HandlerThread { Handler mHandler = null; CameraHandlerThread() { super("CameraHandlerThread"); start(); mHandler = new Handler(getLooper()); } void openCamera() { mHandler.post(new Runnable() { @Override public void run() { oldOpenCamera();//backup } }); } }
  • 10. Lambda Expressions (only in Java 8) private class RandomThread extends Thread { long seed; RandomThread (long seed){ this.seed = seed; } @Override public void run() { Random seededRandom = new Random (seed); rootRandom = seededRandom.nextInt(); } } private Runnable RandomThread = (long seed) -> { Random seededRandom = new Random (seed); rootRandom = seededRandom.nextInt(); } becomes
  • 12. Self Managed Thread Can be Runnables or Thread Closes itself Can Spawn new Threads Example shows linked threads of a simple Socket-level communication app class ConnectThread implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { if (newConnection) { newConnection = false; SocketClass.startClient(); new Thread(new TimeOutThread()).start(); } if (serverReply != null) { if( serverReply.equals(Constants.ACK) ||serverReply.equals(Constants.NAK) ||serverReply.equals(Constants.STOP) { Thread.currentThread().interrupt(); sendCompleteEvent(serverReply); return; } } } } }
  • 13. Executors It’s Super Effective! Executes Runnable Tasks Asynchronous or Sequential New Thread Spawner (new Thread(RunnableTask)).start(); becomes Executor executor = anExecutor(); executor.execute(new RunnableTask()); executor.execute(new NextRunnableTask()); Direct Call in Same Thread class DirectExecutor implements Executor { public void execute(Runnable task) { task.run(); } } Asynchronous Call in new Thread class ThreadPerTaskExecutor implements Executor { public void execute(Runnable task) { new Thread(task).start(); } }
  • 14. ThreadPool Executor Executor which works with a group of maintained “Worker” threads. Threads themselves do not die, but merely transform. Create the Pool ThreadPoolExecutor mThreadPool = new ThreadPoolExecutor( // Initial processor pool size Runtime.getRuntime().availableProcessors(), // Max processor pool size Runtime.getRuntime().availableProcessors(), //Time to Keep Alive 3, //TimeUnit for Keep Alive TimeUnit.SECONDS, //Queue of Runnables mWorkQueue ); Using the Pool public class MyTaskManager { //….. // Run the Task on the Pool mThreadPool.execute( someTask.getRunnable()); //.. Now when done mThreadPool.shutdown(); }
  • 15. Executor Services Control of task that provide Futures (look at this elsewhere) in a single Entity. Examples: ScheuduledExecutorService private class NetworkService implements Runnable { private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException { serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); } public void run() { // run the service try { for (;;) { //Run on the new ThreadPool pool.execute( new Handler(serverSocket.accept())); } } catch (IOException ex) { //This signals shutdown the pool pool.shutdown(); } } } class Handler implements Runnable { private final Socket socket; Handler(Socket socket) { this.socket = socket; } public void run() { // read and service request on socket } } * from developer.android.com
  • 16. RXJava and libraries that have their own Thread Management
  • 17. aka RXAndroid Advantages: Significantly simplifies writing of modules as 3-4 threads can be combined in a single Observable. Very easy to set up communication between multiple “Threads” or RXJava components. Pools and maintains worker threads. Easy to serialize thread results and information. Disadvantages: If not used properly, can have leaked messages and observables. (especially in the hands of those who don’t know thread management). It's not always as perfect in management as a specialty built component. Event and Task based, so self propagating processes are more work to set up.
  • 18. Other Examples of Self Managing Libs RetroFit : Turns Restful API calls into Java interfaces. Handles all Thread management and parsing. (by ReactiveX, many contributions by Square... Lots of Jake Wharton) Bolts-Android : Task based model which works on the premise of Promises (Javascript). Allows easy chaining of Asynchronous tasks. (by Parse and Facebook) Picasso : Image Loader that uses ThreadPoolExecutor to preload and size images. (by Square) Image Loader uses ThreadPoolExecutor and Handlers to preload and resize images. (by Bumptech)