TesujiGoFramework/FlyWeight

Sub-page of TesujiGoFramework

FlyWeight design pattern

Allocating lots of objects can lead to serious performance problems. Although object allocation and the built-in garbage collector of Java are among its most powerful features, they must be used with extreme care in a Go playing program. This is achieved by implementing the FlyWeight pattern whenever possible. It is fine to use the garbage collector in the user-interface and other tools, but within the engine it should not be used.

All data-structures that need to be allocated often therefore must implement the tesuji.core.util.FlyWeight interface. This does nothing but define the required method 'recycle'. Calling this method should be considered the equivalent of a 'free', 'delete' or destructor of the allocated object. How this is implemented will differ from data-structure to data-structure, but most of them will have some kind of pooling mechanism. To complement this, these data-structures will not have a public constructor but will need to be allocated through a static call to some object-pool or factory method. tesuji.games.go.util.FlyWeightFactory is an example of such a factory class.

The obvious disadvantage of this circumvention of the garbage collector is the danger of dangling pointers. Extreme care must be taken that an object is not recycled while still being referenced by an active piece of code. Fortunately it will often be easy to build in monitoring code to catch dangling objects. Even without the availablitiy of a garbage collector this method of object-pooling is an advisable method, as it will perform much better than any general-purpose memory allocation scheme.

Aspect Oriented Programming

To demonstrate how easy it is to check for dangling objects, take a look at tesuji.core.util.DanglingReferenceChecker. This is just a few lines of code and it will throw an IllegalStateException whenever a piece of code is accessing an object that has already been recycled. The exception's stack-trace will show the exact location of the offending piece of code. For this to work you'll need AspectJ however and you may need to get acquainted with Aspect Oriented Programming. Since it's completely separated, you can also do without. You don't need AspectJ to use the framework.


This is a copy of the living page "TesujiGoFramework/FlyWeight" at Sensei's Library.
(OC) 2012 the Authors, published under the OpenContent License V1.0.
[Welcome to Sensei's Library!]
StartingPoints
ReferenceSection
About