Java “too many constants” JVM error

后端 未结 4 1905
广开言路
广开言路 2020-12-16 19:51

I\'m developing an application that generates and compiles classes at runtime. This will sometimes create huge amounts of generated code.

With one of our test cases,

相关标签:
4条回答
  • 2020-12-16 20:15

    http://en.wikipedia.org/wiki/Java_class_file#The_constant_pool

    The constant pool includes numbers, strings, method names, field names, class names, references to classes and methods...basically everything.

    There can be at most 65536 of them.

    0 讨论(0)
  • 2020-12-16 20:16

    I don't know if this is very relevant, but for array constants, EVERY field counts towards it. I'm not quite sure why (my guess is that you don't actually give a literal, and thus the runtime have to put in every value manually, hence needing them all to be constants), but it's like that, and that's the way it is.

    I found that problem when I generated a large cache as an array literal. Since I didn't want to write out 1 000 000 constants by hand, I wrote a small program to write the program for me. I wanted to see how fast the program was when everything was cached from startup.

    (The problem in question is 1.6.1 from "Programming Challenges" by Skiela and Revilla, ISBN 0-387-00163-8)

    So you may have some array somewhere with literals. That is not counted as ONE constant. It's counted as array.length constants. Or array.length + 1 constants.

    0 讨论(0)
  • 2020-12-16 20:17

    Section 5.1 of the JVM spec defines exactly what constitutes the constant pool (mostly references to classes/methods and literals).

    0 讨论(0)
  • 2020-12-16 20:26

    From: JVM Spec

    you can see that the classfile.constant_pool_count has a 'u2' type, which limits it to 65535 entries

    ClassFile {
        u4 magic;
        u2 minor_version;
        u2 major_version;
        u2 constant_pool_count;
        cp_info constant_pool[constant_pool_count-1];
        u2 access_flags;
        u2 this_class;
        u2 super_class;
        u2 interfaces_count;
        u2 interfaces[interfaces_count];
        u2 fields_count;
        field_info fields[fields_count];
        u2 methods_count;
        method_info methods[methods_count];
        u2 attributes_count;
        attribute_info attributes[attributes_count];
    }
    
    0 讨论(0)
提交回复
热议问题