Singleton and Flyweight Patterns

These patterns are related. Singleton ensure only once instance of a class exists;  Flyweight ensures that only one each of a certain key exists.  The aim with each is to reduce resources needed.


In both cases have only private constructors, with public methods for creation/retrieval


Have a static member variable of the class, and have access to it via a geInstance() method.  This will check if the instance is null, if so creates it.  Then returns the instance.


Have a static map, e.g. WeakHashMap or ConcurrentHashMap and check if an instance for your key exists, if so return it, otherwise, create it, put in map and then return it.

private static ConcurrentMap positionMap = new ConcurrentHashMap();

public static PositionId get(String name, PortfolioId portfolio) {

String key = name + "|" + portfolio;PositionId id =


if (null == id) {

synchronized (key) {

id = positionMap.get(key);

if (null == id) {

PositionId newid = new PositionId(name, portfolio);id =

positionMap.putIfAbsent(key, newid);if (null == id) {

id = newid;





return id;