[concurrency-interest] New bug pattern, way to common

Rémi Forax forax at univ-mlv.fr
Sat Mar 22 12:02:55 EDT 2008

Bill Pugh a écrit :
> No, because using the synchronized modifier on a static method 
> synchronizes
> on the Class object.
yes, i know that (JLS
> While this does allow for malicious code to perform denial of service 
> attacks,
> the Java platform is pretty wide open to that.
The problem is that malicious code can be written without any bad intent.

I've seen an example two months ago in a code using a cache to speedup 
some reflection calls
and cause a deadlock between a synchronized static method and a synchronized
block on the same Class objet( used as a value in the cache).

I prefer to stick to that simple rule :
  only synchronize on a non public visible final object.

Note that this rule disallows synchronization on "this" too, which suffers
the same problem.

I understand that pratically FindBugs can't raise a warning on all
synchronized methods because it's a common Java idiom but i think that
allowing synchronized on a method was a bad design decision.

>     Bill
> On Mar 22, 2008, at 9:15 AM, Rémi Forax wrote:
>> Jason Mehrens a écrit :
>>> Another broken pattern that findbugs (1.1.3) doesn't catch is using
>>> getClass() and synchronized.  Since getClass() doesn't always return
>>> the Class object that defines the static field (because of a sub
>>> class) it is a case of synchronized on different objects.  This may
>>> not be common but it is broken.
>> This case is cover by a more general rule: don't synchronized on
>> internable object
>> like Class, String, wrappers (Integer, etc.).
>>> The following is an example, the original was from "yet another broken
>>> double checked locking attempt":
>>> public class NonFinalClassShouldUseClassLiteral {
>>>  private static int count;
>>>  public NonFinalClassShouldUseClassLiteral() {
>>>    synchronized (getClass()) {
>>>      count++;
>>>    }
>>>  }
>>> }
>>> Jason
>> Rémi
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at altair.cs.oswego.edu
>> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list