Java Reference
In-Depth Information
public static synchronized long numCreated() {
return numCreated;
}
}
Alternatively, if you are using release 5.0 or a later release, you can use an AtomicLong instance,
which obviates the need for synchronization in the face of concurrency.
// Thread-safe creation counter using AtomicLong;
import java.util.concurrent.atomic.AtomicLong;
class Creature {
private static AtomicLong numCreated = new AtomicLong();
public Creature() {
numCreated.incrementAndGet();
}
public static long numCreated() {
return numCreated.get();
}
}
Note that it is not sufficient to declare numCreated to be volatile. The volatile modifier
guarantees that other threads will see the most recent value assigned to a field, but it does not make
the increment operation atomic.
 
 
Search WWH ::




Custom Search