For shared counters, there is no need for an explicit MyClassName.class reference. All I did was make the get-and-increment a static synchronized method in the same class in which the counter itself is a static field.

Doing local counters per class is fine, as long as every use of a single counter synchronizes on the same object.

The best solution is to make these counters AtomicInteger or AtomicLong. That builds the concurrency control into the counter itself, eliminating the possibility of synchronization errors. I eagerly await the outcome of the "drop 1.4" vote.

Patricia


Gregg Wonderly wrote:
I think that there is a case either way. Some designs may, in fact want subclasses to share separate counters. Using the explicit MyClassName.class reference will create the shared lock for the super class and all sub classes.

More often than not, I've used this when I wanted the subclasses to stand alone.

Gregg Wonderly

On 2/7/2011 10:00 PM, Patricia Shanahan wrote:
I found a bad synchronization idiom in a couple of the QA test programs for outrigger. I've done what I can to grep for it, but be alert in case it shows up
in code you are reading.

A non-final class needs to assign a unique number to each object of the class,
or any of its direct or indirect subclasses:

// Declared in the class
private static int nextID=0;

// Inside a constructor, or a method called from the constructor
synchronized(getClass()){
id = nextID++;
}

The synchronization is ineffective, because getClass() can return different
Class objects in a non-final class' constructor.

Patricia







Reply via email to