appendix D Understanding Java threads
This appendix discusses the basics of threads in a Java app. A thread is an independent sequential set of instructions your app runs. Operations on a given thread run concurrently with those on other threads. Modern Java applications often depend on multiple threads, which makes it inevitable to encounter situations where you need to investigate why certain threads are not behaving as expected or why they struggle to cooperate with other threads. That’s why you’ll find threads in several discussions throughout this book (especially chapters 7–9, but also here and there in the first half of the book when we discuss debugging). To properly understand this subject matter, you need to know some basics about threads. This appendix introduces foundational concepts essential for understanding other discussions throughout the book.
We’ll start with section D.1, where I’ll remind you of the threads’ big picture and why we use them in apps. We continue in section D.2 with more details on how a thread executes by discussing its life cycle. Knowing the states of a thread’s life cycle and the possible transitions is necessary for investigating any thread-related problems. In section D.3, we discuss thread synchronization, which is a way to control the executing threads. Faulty synchronization implementations introduce most of the problems you need to investigate and solve. In section D.4, we discuss the most common thread-related problems.