One of my coworkers wasn't sure how to fix a UnsynchronizedStaticDateFormatter issue being pointed out by PMD.
So I showed him how. Initially I simply synchronized the method call. And the PMD error went away, and then I thought about what I did a bit more, and realized I was wrong. I synchronized an instance method to fix a problem with a static resource. That's just plain wrong. So I change the code to synchronize on the DateFormatter. My coworker then showed me the PMD docs for the rule, and the example shown was the same as what I first tried. The example for the rule is:
public class Foo {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void bar() {
sdf.format(); // bad
}
synchronized void foo() {
sdf.format(); // good
}
}
I think the example should be like:
public class Foo {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void bar() {
sdf.format(); // bad
}
synchronized void foo() {
sdf.format(); // bad
}
synchronized void barbar() {
synchronized(sdf) {
sdf.format(); // good
}
}
synchronized static void foofoo() {
sdf.format(); // good
}
}
I think the rule needs to be fixed to represent this. I can verify the foo() method above is currently a false negative.
BTW, there is a category of bugs here that perhaps we could solve while looking into this defect. Given a non-thread-safe resource (eg. DateFormatter):
1) Incorrect synchronization on a non-thread-safe static resource.
2) Incorrect synchronization on a non-thread-safe non-static resource for a thread-safe implementation.
Things like DateFormatter would be parameters to such generic rules.