Top Banner
Android Concurrency and background processing Karol Depka Pradzinski Senior Android Developer at Oblong
23

Android Concurrency Presentation

Jan 20, 2017

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Android Concurrency Presentation

Android Concurrencyand background processing

Karol Depka Pradzinski Senior Android Developer at Oblong

Page 2: Android Concurrency Presentation

Meetup topic vote results

Page 3: Android Concurrency Presentation

Strict mode@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { new Socket("localhost", 999); } catch (IOException e) { throw new RuntimeException(e); } }

Page 4: Android Concurrency Presentation

Strict mode

Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144) at java.net.InetAddress.lookupHostByName(InetAddress.java:385) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) at java.net.InetAddress.getAllByName(InetAddress.java:214) at java.net.Socket.tryAllAddresses(Socket.java:108) at java.net.Socket.<init>(Socket.java:177) at java.net.Socket.<init>(Socket.java:149) at com.oblong.example.ExampleActivity.onCreate(ExampleActivity.java:19) at android.app.Activity.performCreate(Activity.java:5372)

Page 5: Android Concurrency Presentation

Strict mode

Page 6: Android Concurrency Presentation

Abstraction layersHigher-Level Utility Libraries Universal Image Loader

Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Page 7: Android Concurrency Presentation

Abstraction layersHigher-Level Utility Libraries Universal Image Loader

Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Page 8: Android Concurrency Presentation

Abstraction layersHigher-Level Utility Libraries Universal Image Loader

Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Page 9: Android Concurrency Presentation

AsyncTaskpublic class MyAsyncTask extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); // Do stuff on UI thread } @Override protected String doInBackground(String... params) { // Do stuff on BACKGROUND thread. // Caveat: usually you need exactly one param, but params[0] is not very elegant/robust this.publishProgress("Progress"); return "Result"; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); // Do stuff on UI thread } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // Do stuff on UI thread } @Override protected void onCancelled() { super.onCancelled(); // Do stuff on UI thread } @Override protected void onCancelled(String s) { super.onCancelled(s); // Do stuff on UI thread } }

Page 10: Android Concurrency Presentation

AsyncTask

MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute("Param"); // OrmyAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // OrExecutorService executor = Executors.newFixedThreadPool(4); myAsyncTask.executeOnExecutor(executor);

Page 11: Android Concurrency Presentation

AsyncTask

MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute("Param"); // OrmyAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Param" /* too easy to forget :-] */); // OrExecutorService executor = Executors.newFixedThreadPool(4); myAsyncTask.executeOnExecutor(executor, "Param" /* too easy to forget :-] */ );

Page 12: Android Concurrency Presentation

No args - Void

Pitfall: var-args - allowing accidental no-args inexecute(Params…)

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

private final String mandatoryParam; public MyAsyncTask(String mandatorySingleParam) { this.mandatoryParam = mandatorySingleParam; } // ...

AsyncTask

Page 13: Android Concurrency Presentation

AsyncTask threadingVersion Default execution

behaviour

October 2008: Android 1.0 single “single background thread”

September 2009: Android 1.6DONUT

multi“pool of threads allowing

multiple tasks to operate in parallel”

February 2011: Android 3.0HONEYCOMB

single+

executeOnExecutor()

“tasks are executed on a single thread to avoid

common application errors caused by parallel

execution”

Page 14: Android Concurrency Presentation

Posting to UI thread// Call from other thread:Runnable runnable = new Runnable() { @Override public void run() { // do stuff on UI thread } }; activity.runOnUiThread(runnable); // Or:new Handler(Looper.getMainLooper()).post(runnable);

public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); // Execute immediately } }

Page 15: Android Concurrency Presentation

Handler, Looper, HandlerThread

HandlerThread ht = new HandlerThread("MyHandlerThread"); ht.start(); Handler h = new Handler(ht.getLooper()); Handler handler = new Handler(ht.getLooper()){ @Override public void handleMessage(Message msg) { //.... } }; h.sendMessage(new MyMessage("MessageParam")); h.post(new Runnable() { @Override public void run() { // do stuff on the handler thread } }); // Alternatives: postAtFrontOfQueue(), postAtTime(), postDelayed()

Page 16: Android Concurrency Presentation

Loader, CursorLoader

• Loads data in the background

• Reacts to changes

• Survives configuration changes

• Topic for another presentation ;-)

Page 17: Android Concurrency Presentation

Abstraction layersHigher-Level Utility Libraries Universal Image Loader

Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Page 18: Android Concurrency Presentation

java.util.concurrent

• Queues: ArrayBlockingQueue, …

• Locks: Lock, ReentrantLock, …

• Atomic: AtomicInteger, AtomicLong, …

• Executor, ThreadPoolExecutor

• CountDownLatch

Page 20: Android Concurrency Presentation

“Java Concurrency in Practice”

@ThreadSafe @Immutable @GuardedBy @NotThreadSafe

Page 21: Android Concurrency Presentation

Abstraction layersHigher-Level Utility Libraries Universal Image Loader

Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Page 22: Android Concurrency Presentation

Higher-Level Utility Libraries Universal Image Loader Library, Volley, …

Android Concurrency Utils AsyncTask, Loader, Handler, Service, …

Java Concurrency Utilsjava.util.concurrent … ThreadPoolExecutor, BlockingQueue, …

Java Concurrency Primitives Object monitors, “synchronized”, volatile, …

Linux threading primitives

Page 23: Android Concurrency Presentation

By the way, we are hiringSenior Android Developer position

Oblong Industries Inc. Barcelona Office