4 Years
Discussion Span
Last Post by JamesCherrill

In practice it's limited by the available memory, but if each instance does not have big data members you can create tens of millions of instances

Edited by JamesCherrill

Votes + Comments
The technical term in "gazillions"... :-)

technically, only 1 class instance is created for any class per classloader.
After that, any number of instance of that class can also be created, as needed, discarded, reused, serialised, deserialised, etc. etc.


Just for fun I created a small class (one int as its members)

class X{
   int i=0;

and an array to keep them in

X[] instances = new X[100_000_000];

then looped creating instances until it ran out of memory

for (int i = 0; i < instances.length; i++) {
    instances[i] = new X();
    if (i % 1_000_000 == 0) {
        System.out.println(i / 1_000_000 + " million");

Using NetBeans with its default memory settings (2 Gig on my 8 Gig machine)it ran for 1 1/2 minutes before crashing with an out of memory exception, having created and kept over 54 million instances.

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.