How commonly do deadlock issues occur in programming?

deadlock

Solution

Deadlocks could arise if two conditions are true: you have mutilple theads, and they contend for more than one resource.

Do you write multi-threaded code? You might do this explicitly by starting your own threads, or you might work in a framework where the threads are created out of your sight, and so you're running in more than one thread without you seeing that in your code.

An example: the Java Servlet API. You write a servlet or JSP. You deploy to the app server. Several users hit your web site, and hence your servlet. The server will likely have a thread per user.

Now consider what happens if in servicing the requests you want to aquire some resources:

if ( user Is Important ){
     getResourceA();
}

getResourceB();

if (today is Thursday ) {
    getResourceA();
} 


// some more code

releaseResourceA();
releaseResoruceB();

In the contrived example above, think about what might happen on a Thursday when an important user's request arrives, and more or less simultaneously an unimportant user's request arrives.

The important user's thread gets Resoruce A and wants B. The less important user gets resource B and wants A. Neither will let go of the resource that they already own ... deadlock.

This can actually happen quite easily if you are writing code that explicitly uses synchronization. Most commonly I see it happen when using databases, and fortunately databases usually have deadlock detection so we can find out what error we made.

Defense against deadlock:

- Acquire resources in a well defined order. In the aboce example, if resource A was always obtained before resource B no deadlock would occur.

- If possible use timeouts, so that you don't wait indefinately for a resource. This will allow you to detect contention and apply defense 1.

Problem

I've programmed in a number of languages, but I am not aware of deadlocks in my code. I took this to mean it doesn't happen. Does this happen frequently (in programming, not in the databases) enough that I should be concerned about it?

Original source