Upload
karol-depka-pradzinski
View
51
Download
0
Embed Size (px)
Citation preview
Android Concurrencyand background processing
Karol Depka Pradzinski Senior Android Developer at Oblong
Meetup topic vote results
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); } }
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)
Strict mode
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, …
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, …
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, …
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 } }
AsyncTask
MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute("Param"); // OrmyAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // OrExecutorService executor = Executors.newFixedThreadPool(4); myAsyncTask.executeOnExecutor(executor);
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 :-] */ );
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
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”
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 } }
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()
Loader, CursorLoader
• Loads data in the background
• Reacts to changes
• Survives configuration changes
• Topic for another 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, …
java.util.concurrent
• Queues: ArrayBlockingQueue, …
• Locks: Lock, ReentrantLock, …
• Atomic: AtomicInteger, AtomicLong, …
• Executor, ThreadPoolExecutor
• CountDownLatch
BlockingQueue
Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable
“Java Concurrency in Practice”
@ThreadSafe @Immutable @GuardedBy @NotThreadSafe
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, …
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
By the way, we are hiringSenior Android Developer position
Oblong Industries Inc. Barcelona Office