If you have two instances of a String, and they are equal, in Java they will share the same memory. How is this implemented under the hood?
EDIT: My application uses a large number of String objects, many of which are identical. What is the best way to make use of Java String constant pool, as to avoid creating custom flyweight implementation?
To apply flyweight pattern, we need to divide Object property into intrinsic and extrinsic properties. Intrinsic properties make the Object unique whereas extrinsic properties are set by client code and used to perform different operations.
Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
String class is designed with Flyweight design pattern. It has similar structure as above example. When you create a string constant, such constant is stored in a pool.
Flyweight is a structural design pattern that allows programs to support vast quantities of objects by keeping their memory consumption low. The pattern achieves it by sharing parts of object state between multiple objects. In other words, the Flyweight saves RAM by caching the same data used by different objects.
If you have two instances of a String, and they are equal, in Java they will share the same memory
This is actually not 100% true.
This blog post is a decent explanation of why this is so, and what the String constant pool is.
Look at the source code of java.lang.String
(the source for entire java api is part of the JDK).
To summarize: A String wraps a subsequence of a char[]
. That backing char[]
is never modified. This is accomplished by neither leaking nor capturing this char[]
outside the String
class. However, several Strings
can share the same char[]
(see Implementation of String.substring
).
There is also the mechanism of interning, as explained in the other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With