Chapter 5. Thread Safety

With the introduction of the java.util.concurrent package in Java 5, threads became commonly used to improve the performance of complex applications. In graphical (or headed) applications, they improve responsiveness by reducing the load on the main thread that processes information to render views—programmed components the user can see and interact with on-screen. When a thread is created within a program that has a concept of a main or UI thread, it’s referred to as a background thread. These background threads often receive and process user interaction events, like gestures and text input; or other forms of data retrieval, like reading from a server; or local stores, like a database or filesystem. On the server side, backend applications using threads have better throughput by leveraging the multiple cores of modern CPUs.

However, using threads has its own risks, as you will see in this chapter. Thread safety can be seen as a set of techniques and good practices to circumvent those risks. Those techniques include synchronization, mutexes, and blocking versus nonblocking. Higher-level concepts like thread confinement are also important.

The goal of this chapter is to introduce you to some important thread-safety concepts that will be used in the following chapters. However, we won’t cover thread safety extensively. For example, we won’t explain object publication or provide details about the Java memory model. These are advanced topics that we encourage ...

Get Programming Android with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.