Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java implement flyweight pattern for string under the hood?

Tags:

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?

like image 643
Dan Avatar asked May 26 '10 02:05

Dan


People also ask

How is flyweight implemented in Java?

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.

How does a flyweight pattern work?

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.

What is the design pattern used in string implementation?

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.

What is flyweight in Java?

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.


2 Answers

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.

like image 105
matt b Avatar answered Sep 23 '22 11:09

matt b


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.

like image 30
meriton Avatar answered Sep 20 '22 11:09

meriton