org.tentackle.appworx
Class AppDbObjectCache<T extends AppDbObject>

java.lang.Object
  extended by org.tentackle.appworx.AppDbObjectCache<T>
Type Parameters:
T - the AppDbObject class

public class AppDbObjectCache<T extends AppDbObject>
extends Object

Cache for AppDbObjects.
The cache works both client- and server side. There can be one cache per class. The cache may hold any number of unique indexes (see AppDbObjectCacheIndex) that can be added or removed at runtime. At ID-index is mandatory and automatically added. Objects may be preloaded on first access (all objects in the current context) or loaded on demand. The cache is also aware of object-lists. For example, a selectAllCached will return a cached list of all objects. And many more features...

Author:
harald

Field Summary
static List<AppDbObjectCache<? extends AppDbObject>> cacheList
          list of all caches
static int FORGET
          forget all entries if maxSize reached (default)
static int LFU
          least frequently used
static int LRU
          least recently used
 
Constructor Summary
AppDbObjectCache(Class<T> objectClazz)
          Creates a cache without preloading.
AppDbObjectCache(Class<T> objectClazz, boolean preload)
          Creates an instance of an AppDbObjectCache.
 
Method Summary
 boolean add(T obj)
          add an object to the cache.
 void addIndex(AppDbObjectCacheIndex<T,?> index)
          Add an index to cache.
 void addIndexIfNotAssigned(AppDbObjectCacheIndex<T,?> index)
          Adds an index if not already added.
static
<T extends AppDbObject>
AppDbObjectCache<T>
createCache(Class<T> clazz, boolean preload)
          Creates an instance of an AppDbObjectCache and registers in a global cache-list (see removeObjectsForDbInAllCaches(org.tentackle.db.Db)).
 void expire(Db db, long maxSerial)
          Expire dirty objects in cache.
 void expire(long maxSerial)
          Same as expire but delayed until the next select.
 void expireByExpirationInfo(long[] expireSet, long curSerial)
          Expires object in cache with an ID of a given set.
 int getKeepQuota()
          Gets the current keep quota.
 int getMaxSize()
          Get the maximum cache size.
 List<T> getObjects()
          Gets all objects in cache.
Because the objects may live in different db-contexts (and different db-connections!) this method should be used with great care in apps as it returns the objects "as is", i.e.
 int getSize()
          Get the number of objects stored in cache.
 int getStrategy()
           
 long getTableSerial()
           
 void invalidate()
          force the cache to be cleared next access
static boolean isAllEnabled()
          Check whether all caches are enabled at all.
 boolean isEnabled()
          Check whether cache is enabled at all.
 boolean isPreloading()
           
 boolean remove(T obj)
          remove an object from cache.
 void removeIndex(AppDbObjectCacheIndex<T,?> index)
          removes an index.
 int removeNonCacheables()
          Removes all objects with isObjectCacheable() == false.
 void removeObjectsForDb(Db db)
          removes all objects and lists for a given Db.
static void removeObjectsForDbInAllCaches(Db db)
          Removes all objects in ALL caches that refer to a given db.
<C extends Comparable<C>>
T
select(AppDbObjectCacheIndex<T,C> index, ContextDb db, C key)
          Retrieve object via cache.
<C extends Comparable<? super C>>
T
select(AppDbObjectCacheIndex<T,C> index, ContextDb db, C key, boolean loadIfMissing)
          Retrieves an object via cache.
<C extends Comparable<? super C>>
List<T>
select(AppDbObjectCacheIndex<T,C> index, ContextDb db, C fromKey, C toKey)
          Retrieve a range of objects from cache.
 T select(ContextDb db, long id)
          common select by ID.
 T select(ContextDb db, long id, boolean loadIfMissing)
          common select by ID.
 List<T> selectAllInContext(ContextDb db)
          Retrieve all objects for a context via cache.
static void setAllEnabled(boolean enabled)
          Set all caches enabled or disabled.
 void setEnabled(boolean enabled)
          Set cache enabled or disabled.
 void setKeepQuota(int keepQuota)
          Set the keep quota in percent for the caching strategy.
 void setMaxSize(int maxSize)
          Set the maximum cache size.
 void setStrategy(int strategy)
          Set the caching strategy.
 void shrinkCache()
          apply caching strategy
 String toString()
          Returns a string representation of the object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

FORGET

public static final int FORGET
forget all entries if maxSize reached (default)

See Also:
Constant Field Values

LRU

public static final int LRU
least recently used

See Also:
Constant Field Values

LFU

public static final int LFU
least frequently used

See Also:
Constant Field Values

cacheList

public static List<AppDbObjectCache<? extends AppDbObject>> cacheList
list of all caches

Constructor Detail

AppDbObjectCache

public AppDbObjectCache(Class<T> objectClazz,
                        boolean preload)
Creates an instance of an AppDbObjectCache.

Parameters:
objectClazz - is the AppDbObject-class managed by the cache.
preload - is true if preload all objects in contextDb of cache.

AppDbObjectCache

public AppDbObjectCache(Class<T> objectClazz)
Creates a cache without preloading.

Parameters:
objectClazz - is the AppDbObject-class managed by the cache.
Method Detail

createCache

public static <T extends AppDbObject> AppDbObjectCache<T> createCache(Class<T> clazz,
                                                                      boolean preload)
Creates an instance of an AppDbObjectCache and registers in a global cache-list (see removeObjectsForDbInAllCaches(org.tentackle.db.Db)). This is the preferred method to create a cache!

Type Parameters:
T - the data object class
Parameters:
clazz - is the AppDbObject-class managed by the cache.
preload - is true if preload all objects in contextDb of cache.
Returns:
the cache

removeObjectsForDbInAllCaches

public static void removeObjectsForDbInAllCaches(Db db)
Removes all objects in ALL caches that refer to a given db. Useful after having closed a db-connection in an RMI-Server, for example.

Parameters:
db - is the db-connection (probably closed)

toString

public String toString()
Description copied from class: java.lang.Object
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 

Overrides:
toString in class Object
Returns:
a string representation of the object.

addIndex

public void addIndex(AppDbObjectCacheIndex<T,?> index)
Add an index to cache. The application need not invoke addIndex explicitly. Assigning the index to the cache will be done automatically on its first use. This is known as deferred index assignment and has the advantage that the index is managed by the cache if really used by the application. However, the application can assign the index explicitly. This will ensure that the index cannot be assigned to another cache accidently.

Parameters:
index - is the index to add

addIndexIfNotAssigned

public void addIndexIfNotAssigned(AppDbObjectCacheIndex<T,?> index)
Adds an index if not already added.

Parameters:
index - the index to add

removeIndex

public void removeIndex(AppDbObjectCacheIndex<T,?> index)
removes an index.

Parameters:
index - to remove

invalidate

public void invalidate()
force the cache to be cleared next access


expireByExpirationInfo

public void expireByExpirationInfo(long[] expireSet,
                                   long curSerial)
Expires object in cache with an ID of a given set.

Parameters:
expireSet - is an array of long-pairs (id/tableserial), sorted by tableSerial, representing the the objects to set expired
curSerial - is the current table serial (from Modification-table), 0 = don't check

expire

public void expire(Db db,
                   long maxSerial)
Expire dirty objects in cache. If the cache does not provide a tableSerial it will be invalidated (i.e. all objects removed). Otherwise, no objects are removed and those marked expired that were changed in the persistance layer. This is done by obtaining the IDs of all objects in the db-table with a tableSerial > cache.tableSerial. See DbObject on how to enable tableSerial for DbObjects. If the cache is preloaded or any selectAllInContext was done, the selectAllLists() will be removed if not all modified objects are in the lists.

Parameters:
db - is the db to use, null = delay expiration check until next select
maxSerial - is the max. tableSerial to scan for updates, 0 = clazz provides no tableSerial

expire

public void expire(long maxSerial)
Same as expire but delayed until the next select.

Parameters:
maxSerial - is the max. tableSerial to scan for updates, 0 = clazz provides no tableSerial

getTableSerial

public long getTableSerial()
Returns:
the highest tableSerial of objects in cache

shrinkCache

public void shrinkCache()
apply caching strategy


getSize

public int getSize()
Get the number of objects stored in cache.

Returns:
the number of objects in cache.

getObjects

public List<T> getObjects()
Gets all objects in cache.
Because the objects may live in different db-contexts (and different db-connections!) this method should be used with great care in apps as it returns the objects "as is", i.e. without checking for key change or expiration. Better use selectAllInContext or select( ... fromKey, toKey).

Returns:
the list of objects

removeNonCacheables

public int removeNonCacheables()
Removes all objects with isObjectCacheable() == false. Useful if the cacheable attribute changes temporarily.

Returns:
the number of objects removed

select

public <C extends Comparable<? super C>> T select(AppDbObjectCacheIndex<T,C> index,
                                                  ContextDb db,
                                                  C key,
                                                  boolean loadIfMissing)
Retrieves an object via cache.

Type Parameters:
C - the Comparable class
Parameters:
index - the cache index to use
db - the contextDb
key - is the Comparable used as a key
loadIfMissing - is true if the object should be loaded from storage if not in cache
Returns:
the object or null if no such object

select

public <C extends Comparable<C>> T select(AppDbObjectCacheIndex<T,C> index,
                                          ContextDb db,
                                          C key)
Retrieve object via cache. Load from storage if not in cache.

Type Parameters:
C - the Comparable class
Parameters:
index - the cache index to use
db - the contextDb
key - is the Comparable used as a key
Returns:
the object or null if no such object

select

public T select(ContextDb db,
                long id,
                boolean loadIfMissing)
common select by ID.

Parameters:
db - the contextDb
id - is the object-ID
loadIfMissing - is true if the object should be loaded from storage if not in cache
Returns:
the object or null if no such object

select

public T select(ContextDb db,
                long id)
common select by ID. Always loads if missing in cache.

Parameters:
db - the contextDb
id - is the object-ID
Returns:
the object or null if no such object

add

public boolean add(T obj)
add an object to the cache. Can be used by apps to add an object explicitly. Will rollback if object (i.e. at least one key) is already in cache. (notice: no initializeMinTableSerial() because we cannot guarantee that the table hasn't been updated between fetching the object and invokation of this method)

Parameters:
obj - is the AppDbObject to add
Returns:
true if added, false if object already in cache

remove

public boolean remove(T obj)
remove an object from cache. Can be used by apps to remove an object explicitly. Does NOT remove the object from any list!

Parameters:
obj - is the AppDbObject to remove
Returns:
true if removed, false if object not in cache

removeObjectsForDb

public void removeObjectsForDb(Db db)
removes all objects and lists for a given Db.

Parameters:
db - is the db-connection (probably closed)

select

public <C extends Comparable<? super C>> List<T> select(AppDbObjectCacheIndex<T,C> index,
                                                        ContextDb db,
                                                        C fromKey,
                                                        C toKey)
Retrieve a range of objects from cache. Objects not in cache so far will NOT be loaded from storage! Furthermore, expired objects will NOT be reloaded from storage and expired objects will be returned in list with isExpired() == true. Thus, reasonably works only if preloading is enabled or a selectAllInContext has been invoked before.

Type Parameters:
C - the Comparable class
Parameters:
index - the cache index to use
db - the contextDb
fromKey - starting key, inclusive
toKey - ending key, exclusive
Returns:
the list of objects

selectAllInContext

public List<T> selectAllInContext(ContextDb db)
Retrieve all objects for a context via cache. Will replace expired objects.

Parameters:
db - the database context
Returns:
the list of objects

isAllEnabled

public static boolean isAllEnabled()
Check whether all caches are enabled at all.

Returns:
Value of property enabled.

setAllEnabled

public static void setAllEnabled(boolean enabled)
Set all caches enabled or disabled.

Parameters:
enabled - New value of property enabled.

isEnabled

public boolean isEnabled()
Check whether cache is enabled at all.

Returns:
Value of property enabled.

setEnabled

public void setEnabled(boolean enabled)
Set cache enabled or disabled. When disabled the cache always reads from storage.

Parameters:
enabled - New value of property enabled.

isPreloading

public boolean isPreloading()
Returns:
true if this is a preloading cache

getMaxSize

public int getMaxSize()
Get the maximum cache size.

Returns:
Value of property maxSize.

setMaxSize

public void setMaxSize(int maxSize)
Set the maximum cache size. Default is 0 = unlimited. If the size is limited the cache will invalidate if exceeded (except in selectAll)

Parameters:
maxSize - New value of property maxSize.

setStrategy

public void setStrategy(int strategy)
Set the caching strategy. The strategy can be changed at any time.

Parameters:
strategy - is one of FORGET, LRU or LFU

getStrategy

public int getStrategy()
Returns:
the cache strategy. Default is FORGET.

setKeepQuota

public void setKeepQuota(int keepQuota)
Set the keep quota in percent for the caching strategy. Will be aligned to [0...100]! Special: 0 is the same as FORGET 100 deletes only one object (this is slow when cache gets full, don't use it!) Reasonable values are 25 up to 75.

Parameters:
keepQuota - in percent

getKeepQuota

public int getKeepQuota()
Gets the current keep quota.

Returns:
the current keep quota, default is 50


Copyright © 2001-2008 Harald Krake, Bergstr. 48, 78098 Triberg, Germany, harald@krake.de