Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java implemented Flyweight design pattern with Strings? [duplicate]

As per the GOF definition for "Flyweight", reuse\share similar kind of objects to reduce the memory growth.

If this is the case, java string object does the same right by using string constant pool. Then can we say that Java String implements the Flyweight design pattern? If not, why?

like image 607
Aditya Avatar asked Feb 06 '23 23:02

Aditya


2 Answers

Can we say that, Java String implements the Flyweight design pattern?

Not really. Or at best you can say that it can implement that pattern.

The string constant pool only contains String objects that correspond to:

  • Java string >>literals<< in the source code,
  • other compile-time string constants, and
  • String objects that have been deliberately "interned" by an application or library method calling the String.intern() method.

Normal Java String objects are not created in the string pool. Instead, they are created in the normal heap, and only "put into the pool" by a call to intern(). This is for good reason. If all strings were interned by default, it would increase GC overheads and/or the long-term memory footprint of a typical Java application.

(Note that Java 8 now has an optional string deduplication feature in the G1 collector which saves space by combining the char arrays of strings that are equal.)

like image 102
Stephen C Avatar answered Feb 09 '23 11:02

Stephen C


Yes, Java's string pool is a good example of the flyweight pattern. As stated by the wikipedia article on the subject:

Another example [of this pattern] is string interning.

like image 22
Mureinik Avatar answered Feb 09 '23 13:02

Mureinik