Summary
As mentioned at the start of this chapter, Java’s native support of threads is one of the reasons for its popularity. In this chapter, we saw how we can create threads by extending the Thread
class and by implementing either a Runnable
or Callable
interface. We saw how ExecutorService
allows us to pool threads. We concluded by looking at one specific issue, where two or more threads compete for access to a shared resource, called a race condition, and saw how we resolve this by applying locks through the application of synchronization.
There are changes coming to threading. Project Loom, at the time of writing, introduces threads managed exclusively by the JVM along with a framework for concurrency. Some features are in preview, while others are in incubation. It will be a few years before these new types of threads become commonplace. I recommend following the development of this project.
In our next chapter, we will look at the most used design patterns in Java...