SlideShare ist ein Scribd-Unternehmen logo
1 von 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!

Weitere ähnliche Inhalte

Was ist angesagt?

Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Григорий Шехет "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"Fwdays
 
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 2010Nicholas Zakas
 
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)Kelly Shuster
 
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 09Fred Sauer
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Aug penguin16
Aug penguin16Aug penguin16
Aug penguin16alhino
 
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.ioKaty Slemon
 
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 SwiftRay Deck
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Tomek Kaczanowski
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBMichal Bigos
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesHassan Abid
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modulesRafael Winterhalter
 
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)Ondřej Machulda
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JSJacob Nelson
 

Was ist angesagt? (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
 

Andere mochten auch

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 testingGDG Korea
 
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/16Stacy Devino
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGDG Korea
 
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 Devicesjuricde
 
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!Stacy Devino
 
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출GDG Korea
 
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법
같은 유저수, 다른 수익? 모바일 앱의 수익을 높이는 방법GDG Korea
 
디자이너 없어도 괜찮아! (feat.Material Design Guide)
디자이너 없어도 괜찮아! (feat.Material Design Guide)디자이너 없어도 괜찮아! (feat.Material Design Guide)
디자이너 없어도 괜찮아! (feat.Material Design Guide)GDG Korea
 
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?
GKAC 2014 Nov. - Android Wear 개발, 할까요 말까요?GDG Korea
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 
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 ProgrammingGDG Korea
 
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지
GKAC 2015 Apr. - 테스트 코드에서 코드 커버리지까지GDG Korea
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media PlaybackGDG Korea
 
FIrebase를 이용한 호우호우 미니게임 만들기
FIrebase를 이용한 호우호우 미니게임 만들기FIrebase를 이용한 호우호우 미니게임 만들기
FIrebase를 이용한 호우호우 미니게임 만들기GDG Korea
 
Reinfocement learning
Reinfocement learningReinfocement learning
Reinfocement learningGDG Korea
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩GDG Korea
 
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 2016GDG Korea
 
Tomcat Optimisation & Performance Tuning
Tomcat Optimisation & Performance TuningTomcat Optimisation & Performance Tuning
Tomcat Optimisation & Performance Tuninglovingprince58
 
Android - Preventing common memory leaks
Android - Preventing common memory leaksAndroid - Preventing common memory leaks
Android - Preventing common memory leaksAli Muzaffar
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 

Andere mochten auch (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
 

Ähnlich wie Async task, threads, pools, and executors oh my!

Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
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 & JetpackNelson Glauber Leal
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threadingVitali Pekelis
 
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 JetpackNelson Glauber Leal
 
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 applicationsMatteo Manchi
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Lifeparticle
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
[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 ServerlessKatyShimizu
 
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.jssoft-shake.ch
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adaptersVitali Pekelis
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
Introduction to nodejs
Introduction to nodejsIntroduction to nodejs
Introduction to nodejsJames Carr
 
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 & JetpackNelson Glauber Leal
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer 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 WindowsPhoneMohammad Shaker
 

Ähnlich wie 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
 

Mehr von Stacy Devino

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 2018Stacy Devino
 
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 SpannablesStacy Devino
 
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 improvedStacy Devino
 
Big Trouble in Little Networks
Big Trouble in Little Networks Big Trouble in Little Networks
Big Trouble in Little Networks Stacy Devino
 
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 devinoStacy 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 HackerStacy Devino
 

Mehr von 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
 

Kürzlich hochgeladen

Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
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.pdfKamal Acharya
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
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 in Nagpur High Profile
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 

Kürzlich hochgeladen (20)

Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
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
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
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...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 

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)