2010-07-13

Is there a general way to code to avoid concurrency problems?

(...) Brian Goetz pointed it out to me. (...) The technique is to never write any multi-threading or synchronizing code, except in specialist classes which handle all the issues under the covers.

Ideally, you use what has already been developed by the experts out there: use ConcurrentHashMap rather than HashMap as your default Map; use a BlockingQueue to pass things between threads without having to think about synchronization to share the data; GC is dirt cheap now for short-lived objects so don't think twice about copying out data to a temporary object for manipulation or iterating; and so on.

(...) Inevitably you will have to write some classes yourself that handle concurrency issues. (...) You should isolate that concurrency managing code into separate dedicated classes and, most importantly, spend a lot of time getting those classes right and reusable because concurrency is hard, even for the experts.

--Jack Shirazi

No comments: