javaflyweight-pattern

How is the same object returned multiple times in flyweight design pattern


I have an example which demonstrates flyweight design pattern, where there are soldiers in a game. This soldier instance has to be used by multiple clients simultaneously. And thislink says the same object is returned if it is available in the map (or cache). Isn't this unsafe to use same object concurrently as a thread may change its property.


Solution

  • Yes. A flyweight pattern should only be used with immutable objects, regardless whether it is used in a single thread or in a multi-thread environment.