Concurrency Discussions on LinkedIn

Several months ago I mentioned that I posted a question about using the “synchronized” keyword for concurrency to a few LinkedIn groups. I recalled that a speaker at No Fluff Just Stuff said that a good rule of thumb is to declare your variables private, and to mark any methods that alter them with the “synchronized” keyword. I had heard that concurrency is complicated. Was the speaker’s advice too good to be true?

Perhaps. A lot of the responders said that if you synchronize a method, the JVM gets a lock on the object. This could cause deadlock if another thread also tries to call that method. Plus if you mark too many methods as synchronized then you could have performance issues, since the JVM has to acquire and release the same lock over and over.

Several responses suggested using synchronized blocks with a different object for each block. This would cause less contention and there would be less chance for deadlock. There was some debate whether there would be any performance hits due to locking. But deadlocks were mentioned quite a bit.

A few people suggested avoiding lock-based concurrency and to instead look at the java.util.concurrency packages.

Someone suggested I look at Brian Goetz’s book. Another poster pointed out that “Brian elaborates on it for good four hundred pages.”  Which is a reason to not read it. I keep thinking that something this important should be easier.

Image from Wikimedia, assumed allowed under Fair Use. Image from the Vatican Virgil, a 5th century manuscript of poems by Virgil.