File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Architect Certification (SCEA/OCMJEA) and the fly likes Regarding Flyweight pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Architect Certification (SCEA/OCMJEA)
Bookmark "Regarding Flyweight pattern" Watch "Regarding Flyweight pattern" New topic

Regarding Flyweight pattern

Paritosh H Chandorkar
Ranch Hand

Joined: Nov 11, 2012
Posts: 89
Hello All,

I have yet not understood the logic of the FlyWeight pattern implementation.
Can you please explain me in brief with suitable example?
Please do share the useful links as well.

Thanks and regards,
Paritosh Chandorkar
Jelle Klap

Joined: Mar 10, 2008
Posts: 1948

The Flyweight pattern is basically all about resource management, more specifically about supporting large numbers of objects efficiently by encapsulating state in an immutable object (the flyweight) and sharing that object among as many similar objects as possible. One example of a flyweight implementation is actually a well-known mechanism provided by the core Java API: java.lang.String.intern(). XML parsers, for instance, can use the String.intern() mechanism to efficiently share XML tag names (among other things) when processing XML data. Building a complete DOM tree in-memory is already notoriously expensive when it comes to memory consumption. Imagine how much more expensive it would be if the XML parser would have to allocate heap space for a new String object for each and every tag it encouters, regardless of whether or not it had already processed tags with an identical name. A String is immutable by design and the String.intern() method offers a convenient way to add a new value to the constant pool at runtime, so an XML parser can make use of this to keep the number of String objects related to tag names in check. This is the essence of the Flyweight pattern, which in this example is facilited by an object pool. To reiterate, a flyweight object is an immutable object that encapsulates state that can be shared among many other objects - immutability is key because state must be shared safely.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Paritosh H Chandorkar
Ranch Hand

Joined: Nov 11, 2012
Posts: 89
Thanks a lot Jelle,for the reply.I got a hang of it now.
I agree. Here's the link:
subject: Regarding Flyweight pattern
jQuery in Action, 3rd edition