|
|
|
Back to newsletter 115 contents
Threads, threads, threads. I gave some interesting examples of concurrency issues in my talk last month, and I showed how to identify and resolve them. I was interested to see that the audience found these examples just as challenging as when I first encountered them "in the wild" - i.e. in the production systems I was troubleshooting when I first found them. But there was one particular question that I want to address here: is there a general way to code to avoid concurrency problems?
The answer is yes. It's not a technique I thought of, in fact it was my own concurrency guru, Brian Goetz (who is still with Oracle after the Sun takeover), who 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.
Of course, sadly there is not a data structure for every, or even most, of the code problems you need to solve. So inevitably you will have to write some classes yourself that handle concurrency issues. The point that Brian made to me was that 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.
If you find yourself writing concurrency handling code in some method you are implementing, then you need to stop and think: where should that code actually be? Because I shouldn't be writing this here, it should be abstracted away into some handling class which will allow me to write this code without explicit concurrency management. Easier said than done, of course, but the payback in reduced incidents and maintenenance costs is well worth it.
Now on with this month's newsletter. We have all our usual Java performance tools, news, and article links, though no Javva The Hutt as he preferred Glastonbury to the rigour of his column deadline. Over at fasterj we have a new cartoon showing where the application spends its time; and, as usual, we have extracted tips from all of this month's referenced articles.
Java performance tuning related news.
Java performance tuning related tools.
Back to newsletter 115 contents