Tuesday, January 13, 2009

Flyweight Pattern

Flyweight design pattern is a software design pattern used to minimize memory usage by sharing data. It enables use of large number of objects that would typically require a lot of memory.

A common example of the Flyweight pattern is string pooling. Consider the Java programming language. The String data type is immutable. Because it is guaranteed that the string can never be changed the strings are pooled to ensure that only one instance exists in memory at any given time.

So if you create two strings s1 and s2 which both point to "foo" you really have two pointers to the same location in memory.

Java also employs the Flyweight pattern for Integer object. new Integer(0) actually returns a pointer to pre-constructed object. So if you create one-thousand Objects which each contain an Object of type Integer you will only have one Integer(0) which is an excellent way to save memory.

While your writing your programs consider if you could use the Flyweight pattern to save memory. An example I used was for a Object that contained three Strings. This tuple uniquely identified a configuration of runs that were stored in the database. The Strings were loaded via JDBC so they didn't get the String pooling provided by Java. Instead I made the constructor to the class private and exposed a public static method called 'get'. This method took the three strings and created the object if not already existing and returned a pointer. This cut my memory usage drastically.

Here is an example of my use of the Flyweight pattern.


class Product {
private Product() { } // don't let anyone explicitly create this object.
private static Map products = new HashMap();
public get(String arch, String chip, String config) {
Product p = products.get(arch + chip + config).hashCode());
if (p == null)
products.put(arch + chip + config).hashCode(),new Product(arch,chip,config));
return products.get(arch + chip + config).hashCode());
}
}


If your using c++ you should look at the boost flyweight class. It hides the implementation and makes adding a flyweight to your c++ code trivial. http://svn.boost.org/svn/boost/sandbox/flyweight/libs/flyweight/doc/index.html

2 comments:

bangoura said...

Hello,
your article is great! But it is going to be interestint if you write a full example with test code, so that the newer better understand :-)!
King regards

JE@Java main method said...

This is a good article. I have also created a blog post on Java flyweight design pattern with some code extract for String class.