depsypher
depsypher

Reputation: 1219

Does declaring many identical anonymous classes waste memory in java?

I recently ran across the following snippet in an existing codebase I'm working on and added the comment you see there. I know this particular piece of code can be rewritten to be cleaner, but I just wonder if my analysis is correct.

Will java create a new class declaration and store it in perm gen space for every call of this method, or will it know to reuse an existing declaration?

protected List<Object> extractParams(HibernateObjectColumn column, String stringVal) {
    // FIXME: could be creating a *lot* of anonymous classes which wastes perm-gen space right?
    return new ArrayList<Object>() {
        {
            add("");
        }
    };
}

Upvotes: 12

Views: 2757

Answers (4)

user207421
user207421

Reputation: 310956

Does declaring many identical anonymous classes waste memory in java?

Of course it does but you're not doing that in the code you posted.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718906

The other answers are correct.

However:

  • If that pattern is repeated a number of times in your code, then you will end up with an equal number of inner classes. If you use the pattern hundreds / thousands of times, the increased code footprint / permgen usage could be significant.

  • What you are doing in this particular example could be expressed more simply as

    protected List<Object> extractParams(HibernateObjectColumn column, 
                                         String stringVal) {
        return Collections.singletonList("");
    }
    
  • For cases where you have to populate the list with multiple values, a solution involving a static helper method is probably simpler.

Upvotes: 4

Michael Ekstrand
Michael Ekstrand

Reputation: 29090

The class will only be compiled once (at compile time). The compiler extracts a class (named something like MyOuterClass$1) and uses it. It will create multiple instances, of course, but they will all be of the same class. You can see that when you compile the .java file and look at the .class files generated - there will be one for the inner anonymous class.

Upvotes: 18

C. K. Young
C. K. Young

Reputation: 223073

No, that creates many instances of one single class. To test, put this within your anonymous class:

@Override
public String toString() {
    return getClass().getName();
}

Then call toString() on various instances of the anonymous class. You'll see they all return the same class name.

Upvotes: 5

Related Questions