This section explains how to write a custom cache algorithm
to meet specific application requirements. The example in this section
is a simplified version of the class
IlvDefaultTileCache provided in the
JViews Maps library.
The complete source code for this example can be found
in the following file:
The class SimpleTileCache
extends
the class IlvTileCache
.
public class SimpleTileCache
extends IlvTileCache
{
cacheSize
defines the maximum
number of tiles that can be stored in the cache.
// default cache size
private int cacheSize = 5;
// To Store the tiles
transient private Vector tiles = new Vector();
The following constructor creates an instance of the
default cache with the specified size (in this example, 5).
public SimpleTileCache(int size)
{
cacheSize = size;
}
The following constructor reads the cache from the provided
input stream. Caches created using this constructor implement the
IlvPersistentObject interface and can thus be saved with an
IlvTiledLayer
object.
public SimpleTileCache(IlvInputStream stream)
throws IlvReadFileException
{
cacheSize = stream.readInt("size");
}
The write()
method writes
the cache to an output stream.
public void write(IlvOutputStream stream)
throws IOException
{
super.write(stream);
stream.write("size", cacheSize);
}
The following method belongs to the
IlvTileCache interface. It is called when a tile is cached. In
this implementation, the tile is added at the end of the internal
tile list.
public void tileCached(IlvTile tile)
{
tiles.addElement(tile);
}
The following method belongs to the
IlvTileCache interface. It is called when a tile is removed from
the cache and locked again. With this implementation, the tile is
removed from the internal tile list.
public void tileRetrieved(IlvTile tile)
{
tiles.removeElement(tile);
}
The following method belongs to the
IlvTileCache interface. It is called when a tile is about to
be loaded. With this implementation, if the number of tiles in the
cache exceeds the cache size, the least recently used tiles, at the
top the internal tile list, will be unloaded to make room for new
tiles.
public void tileAboutToLoad(IlvTile tile)
{
int toRemove = tiles.size() - cacheSize;
if (toRemove <= 0)
return;
for (int i = toRemove; i > 0; i--) {
IlvTile current = (IlvTile) tiles.elementAt(0);
tiles.removeElementAt(0);
releaseTile(current);
}
}
The following method belongs to the
IlvTileCache interface. It is called when a tiled layer is taken
out of the manager to remove the tiles managed by its tile controller
from the cache.
public void controllerDisposed(IlvTileController controller)
{
int i = 0;
while (i < tiles.size()) {
IlvTile tile = (IlvTile) tiles.elementAt(i);
if (tile.getController() == controller)
tiles.removeElementAt(i);
else
i++;
}
}