Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
<p>
     This instance method synchronizes on <code>this.getClass()</code>. If this class is subclassed,
     subclasses will synchronize on the class object for the subclass, which isn't likely what was intended.
     For example, consider this code from java.awt.Label:
     <pre>
     private static final String base = "label";
     private static int nameCounter = 0;
     String constructComponentName() {
        synchronized (getClass()) {
            return base + nameCounter++;
        }
     }
     </pre></p>
     <p>Subclasses of <code>Label</code> won't synchronize on the same subclass, giving rise to a datarace.
     Instead, this code should be synchronizing on <code>Label.class</code>
      <pre>
     private static final String base = "label";
     private static int nameCounter = 0;
     String constructComponentName() {
        synchronized (Label.class) {
            return base + nameCounter++;
        }
     }
     </pre></p>
      <p>Bug pattern contributed by Jason Mehrens</p>
New to GrepCode? Check out our FAQ X