Chapter  5

Multithreading and Synchronization

Chapter 1 introduced the concept of the main thread, or UI thread, in which most events are handled. Even though you are not prevented from executing all your code from within the main thread, your application typically uses more than one thread. As a matter of fact, several threads are created and run as part of your application even if you don’t create new threads yourself. For example, Eclipse’s DDMS perspective shows these threads when an application runs on an Android 3.1-based Galaxy Tab 10.1:

  • main
  • HeapWorker
  • GC (Garbage Collector)
  • Signal Catcher
  • JDWP (Java Debug Wire Protocol)
  • Compiler
  • Binder Thread #1
  • Binder Thread #2

So far, we’ve discussed only the first one in the list, the main thread, so you probably were not expecting these extra seven. The good news is that you don’t have to worry about these other threads, which exist mostly for housekeeping; besides, you don’t have much control over what they actually do. Your focus should be on the main thread and on not performing any long operation within that thread, to keep your application responsive.

The particular housekeeping threads Android spawns depends on which Android version an application is running on. For example, Android 2.1 generates six threads (as opposed to the eight listed above) because garbage collection takes place in a separate thread only in Android 2.3 and above, and the Just-In-Time compiler was not introduced until Android 2.2.

In this chapter you learn how to create your own threads, how to communicate between them, how objects can safely be shared between threads, and how, in general, you can tailor your code to take full advantage of your device's multithreading capabilities. We also review common pitfalls to avoid when working with threads in an Android application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.77.21