SlideShare uma empresa Scribd logo
1 de 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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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] 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
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] 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
 

Semelhante a 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] 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
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] 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
 

Mais de 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
 

Mais 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
 

Último

Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptxNikhil Raut
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 

Último (20)

Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 

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)