4

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Aditya
  • 115
  • 1
  • 9
  • I think this might answer your question. http://stackoverflow.com/questions/2909848/how-does-java-implement-flyweight-pattern-for-string-under-the-hood – Dale May 22 '16 at 06:38
  • I looked into it, it doesn't have proper reason why not? – Aditya May 22 '16 at 07:24

2 Answers2

6

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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • What do you mean by normal java strings? Every string in java is a constant correct? So it should create in Constant pool right? – Aditya May 22 '16 at 09:26
  • 2
    I mean a String that is created by calling one of the string constructors or method (apart from `intern`). The fact that strings are immutable does not mean they are (necessarily) created in the pool. – Stephen C May 22 '16 at 22:30
  • If you don't believe me, check the Java source code. – Stephen C May 22 '16 at 22:42
2

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    The Wikipedia article is correct but IMO your conclusion is not entirely correct. String _interning_ is an example of the pattern but that doesn't apply to "Java String" (term used by OP) as a whole. – Marcel Stör May 22 '16 at 21:59
  • 1
    Interning is closer to caching than flyweight. IMHO the lines are blurred here though. – Bohemian May 23 '16 at 04:55