DZone

Thread synchronization is a great tool to overcome race conditions in multithreaded programs. But, it also has a dark side; deadlocks: nasty errors that are difficult to discover, reproduce, and fix. The only surefire way to prevent them is properly designing your code, which is the subject of this article. We will take a look at the origin of deadlocks, consider a method for discovering potential deadlocks in existing code, and present practical approaches to designing a deadlock-free synchronization. The concepts will be illustrated with a simple demo project.

It is assumed that the reader is already familiar with multithreaded programming and has a good understanding of thread synchronization primitives in Java. In the following sections, we will not distinguish between the synchronized statements and the lock API, using the term “lock” for reentrant locks of both types, preferring the former in the examples.

Source: DZone