Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring many identical anonymous classes waste memory in java?

Tags:

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("");
        }
    };
}
like image 925
depsypher Avatar asked Jan 11 '11 02:01

depsypher


2 Answers

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.

like image 66
Stephen C Avatar answered Sep 19 '22 19:09

Stephen C


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.

like image 34
Michael Ekstrand Avatar answered Sep 21 '22 19:09

Michael Ekstrand