In the previous two chapters, I focused on the pitfalls of writing multithreaded applications in Java. With this chapter, I’ll show you a few solutions to the problems. I’ll start out with a look at a roll-your-own mutex class that is easier to use than synchronized in some situations. In particular, it allows you to specify a timeout so that you won’t have to wait forever to acquire a lock (as compared to synchronized, which provides no timeout facility). We’ll also look at a lock manager class that lets you safely acquire multiple semaphores without deadlocking. Using objects of these classes rather than the built-in synchronized can save you hours of searching for unexpected deadlocks, and though these classes don’t solve every possible deadlock problem, they’re still pretty useful.
KeywordsThread Block Strategy Pattern Personal Purpose Class File Spin Lock
Unable to display preview. Download preview PDF.