Java: Why is constant pool maintained only for String values ?

前端 未结 2 1233
情话喂你
情话喂你 2021-02-05 19:19

My question is about java interning and constant pools.

Java maintains a a constants pool for java.lang.String, to use JVM memory cleverly, and to do so jav

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 19:44

    The purpose of a constant pool is to reduce the memory overhead required by keeping multiple copies of constants. In the case of Strings, the JVM is inherently required to keep some object around for each individually distinguishable constant, and the Java spec basically says that the JVM should deduplicate String objects when class loading. The ability to manually place Strings in the pool via intern is inexpensive and allows programmers to identify particular values (such as properties) that are going to be around for the life of the program and tell the JVM to put them out of the way of normal garbage collection.

    Pooling numeric constants, on the other hand, doesn't make a lot of sense, for a few reasons:

    • Most particular numbers aren't ever used in a given program's code.
    • When numbers are used in code, embedding them in the code as immediate opcode values is less expensive in terms of memory than trying to pool them. Note that even the empty String carries around a char[], an int for its length, and another for its hashCode. For a number, by contrast, a maximum of eight immediate bytes is required.
    • As of recent Java versions, Byte, Short, and Integer objects from -128 to 127 (0 to 127 for Character) are precached for performance reasons, not to save memory. This range was presumably chosen because this is the ranged of a signed byte, and it will cover a large number of common uses, while it would be impractical to try to precache a very large number of values.

    As a note, keep in mind that the rules about interning were made long before the introduction of autoboxing and generic types in Java 5, which significantly expanded how much the wrapper classes were casually used. This increase in use led Sun to add those common values to a constant pool.

提交回复
热议问题