Note that while this will tell you how many have been CREATED, that does not tell you how many are currently ALIVE. You could easily write a for loop that creates 100 objects and immediately discards the reference, making them all eligible for garbage collection. And you have no way to know when that may happen.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
How to judge which objects are eligible for garbage collection. This code extract has been taken from Johnathan Giles java note. The explantion given by him is confusing me. Here it is ....
Even when e3 and e2 are set to be null, it is
not possible to do any garbage collection,
even though it feels like it should be possible
to garbage collect e2.
This is because e2 is still accessible from e1,
indirectly. E1.e refers to the original e3, and
e3.e still refers to the original e2.
Therefore, no garbage collection is possible
until all three objects are set to null, and they
become an island of references ready for GC.
Thanks & Regards
Joined: Oct 13, 2005
That is a question unrelated to the original thread. Please post that as a new thread; asking unrelated questions is called hi-jacking and can deprive the original poster of contact with their thread.
So my guess is that it would be threadsafe if the two lines were inside a "synchronized" constructor:
Better? I'm not really sure about this....
I think the problem with my class is the bar is set pretty low. They care that things compile and work correctly. No one talks about more advanced things. With some of the responses I've gotten from the graders, I bet not many people put much effort into their projects.
Joined: Oct 22, 2009
Janeice DelVecchio wrote:Better? I'm not really sure about this....
This is a threadsafe version of the class. You can't synchronize a constructor so instead a static creation method is introduced. The actual increment can alternatively be made in the private constructor. Many would prefer that for reasons of clarity.
Now objects can be created from any thread and you don't risk having two objects with the same number.
But "getInstance" suggests you're going to be getting an instance which already exists, as in a singleton class. If you look through the Java API documentation, there's a large number of methods named getInstance, but they are all (I think) static members of their classes. That's the static factory pattern. Methods which genuinely create a new instance tend to be called newInstance, and there's about 50 of those in the Java API. Some of those are static members, too, but quite a few are not.
There aren't any "createInstance" methods in the API, but there's a long list of "createThis" and "createThat". So a method which creates a Widget could be called "createWidget".