Java Reference
In-Depth Information
}
Note, however, that the program is not using the local variable
creature
. Therefore, it makes more
sense to replace the declaration with a naked constructor invocation, emphasizing that the reference
to the newly created object is being discarded:
for (int i = 0; i < 100; i++)
new Creature();
If either of these changes is made, the program will print
100
as expected.
Note that the variable used to keep track of the number of
Creature
instances (
numCreated
) is a
long
rather than an
int
. It is quite conceivable that a program might create more instances of some
class than the maximum
int
value but not the maximum
long
value. The maximum
int
value is
2
31
- 1, or about 2.1 x 10
9
; the maximum
long
value is 2
63
- 1, or about 9.2 x 10
18
. Today, it is
possible to create about 10
8
objects per second, which means that a program would have to run
about three thousand years before a
long
object counter would overflow. Even in the face of
increasing hardware speeds,
long
object counters should be adequate for the foreseeable future.
Also note that the creation counting strategy in this puzzle is not thread-safe. If multiple threads can
create objects in parallel, the code to increment the counter and the code to read it must be
synchronized:
// Thread-safe creation counter
class Creature {
private static long numCreated;
public Creature() {
synchronized (Creature.class)
{
numCreated++;
}
}
Search WWH ::
Custom Search