[concurrency-interest] New bug pattern, way to common
gregg at cytetech.com
Sun Mar 23 14:19:31 EDT 2008
Luke Blanshard wrote:
> This is still buggy. Suppose you added class C extends A, and have
> thread 1 create an A and thread 2 create a C. Now the inc method will
> be able to run simultaneously in both threads.
> It would only make sense to synchronize on getClass if there were "class
> instance" variables in Java, as in some variants of Smalltalk.
I don't know that I have a great example of when this behavior would actually be
correct. It seems like findbugs could alert one to refererences to non-final
or non-private references within synchronized(getClass()) blocks. I.e.
getClass() is okay as long as it's referencing things that only this "Class"
instance can see. As in this example, that would include instance variables as
well as methods. If increment() were final or private, then it's reference
would be okay. It might also be okay to reference methods that were abstract.
So, I'm not sure that this could be called a problem coding practice as much as
an advanced coding construct that needs careful attention to use correctly.
More information about the Concurrency-interest