Alex Rivera | Logout

What are common concurrency pitfalls?

Asked 2009-02-06T15:56:29.537
35

I'm looking into educating our team on concurrency. What are the most common pitfalls developers fall into surrounding concurrency. For instance, in .Net the keyword static opens the door to a lot of concurrency issues.

Are there other design patterns that are not thread safe?

Update

There are so many great answers here it is difficult to select just one as the accepted answer. Be sure to scroll through them all for great tips.

Edit
Report

2 Answers

1

One concurrent programming pitfall is improper encapsulation leading to races and deadlocks. This can probably happen in lots of different ways, though there are two in particular that I've seen:

  1. Giving variables unnecessarily wide scope. For example, sometimes people declare a variable at instance scope when local scope would do. This can create the potential for races where none need exist.

  2. Exposing locks unnecessarily. If there's no need to expose a lock, then it's consider keeping it hidden away. Otherwise clients may use it and create deadlocks that you could have prevented.

Here's a simple example of #1 above, one that's pretty close to something I saw in production code:

public class CourseService {
    private CourseDao courseDao;
    private List courses;

    public List getCourses() {
        this.courses = courseDao.getCourses();
        return this.courses;
    }
}

In this example there's no need for the courses variable to have instance scope, and now concurrent calls to getCourses() can have races.

answered 2009-02-09T08:08:16.360
0

Some canonical pitfalls are deadlocks (two competing processes are stuck waiting for each other to release some resource) and race conditions (when the timing and/or dependence of events can lead to unexpected behavior). Here is a worthwhile video about "Multithreading Gotchas" as well.

answered 2009-02-06T16:00:36.423

Your Answer