A Taste of Some Concurrency Patterns
In the previous chapter, we touched upon the problem of races. We have race conditions in real life too! The next example is a little hypothetical. People don't miss one another that much, given the technology available these days. However, let's pretend we don't have this technology (I know it's hard to imagine it—let's just pretend for a while though). Let's say it's a Friday and I come home, planning to go for dinner and a movie. I call my wife and daughter, and they reach the movie theater a little ahead of time. However, while driving back home, I get caught in the Friday evening rush and get delayed in traffic. Because I'm running so late, my wife decides to take a stroll and decides to call on a friend working nearby for a cozy chat.
Meanwhile, I arrive at the movie theater, park my car and rush to the movie theater. However, my wife is nowhere to be seen so I decide to check the nearby diner.
By the time I'm in the diner, my wife arrives at the movie theater and doesn't find me there. So, she decides to check the parking lot.
This could go on and on and we could end up missing our Friday movie and dinner in the process. But, thanks to the cell phone, we can easily synchronize our movements and meet each other in time for the movie.
In this chapter, we will look at a thread's context. Understanding this concept is central to understanding the way Java's concurrency works. We start by looking at the singleton design pattern and the problem of a shared state. However, let's look at some background information first.