Named caches provide a mechanism to control the caching policy of managed objects. Named caches can be created using either the administrative tools or an API. Named caches can be dynamically created and destroyed while an application is running. When managed object classes are associated with the named cache the caching policies defined by the named cache are applied.
The Example 5.27, “Named cache creation” creates a zero-byte named cache and associates a managed object class with the cache. When the cache is flushed by the background flusher thread, the created object is deleted, the delete trigger is called, and the object is removed from shared memory.
Example 5.27. Named cache creation
// $Revision: 1.1.2.2 $ package com.kabira.snippets.managedobjects; import com.kabira.platform.CacheManager; import com.kabira.platform.CacheManager.Cache; import com.kabira.platform.DeleteTrigger; import com.kabira.platform.Transaction; import com.kabira.platform.annotation.Managed; /** * Defining a named cache * <p> * <h2> Target Nodes</h2> * <ul> * <li> <b>domainnode</b> = A * </ul> */ public class NamedCache { @Managed private static class A implements DeleteTrigger { @Override public void uponDelete() { System.out.println("INFO: Object deleted"); m_deleted = true; } }; /** * Main * * @param args Arguments - none supported * @throws InterruptedException */ public static void main(final String[] args) throws InterruptedException { createNamedCache(); // // Create an object in the just created named cache // new Transaction() { @Override protected void run() throws Transaction.Rollback { new A(); } }.execute(); // // Wait for the flusher to delete the local // object when it is flushed from the cache // while (m_deleted == false) { Thread.sleep(1000); } } // // Create a zero byte named cached. // Objects in the cache will be flushed // by the back-ground flusher thread. // private static void createNamedCache() { new Transaction() { @Override protected void run() throws Transaction.Rollback { Cache cache = CacheManager.getOrCreateCache(A.class.getSimpleName()); cache.setSizeBytes(0); cache.addClass(A.class); } }.execute(); } private static boolean m_deleted = false; }
The snippet outputs these messages when it is run:
INFO: Object deleted
The created cache can be displayed using the administrator command line tool after the snippet is executed:
administrator servicename=A display cache Name = A Objects In Cache = 0 Cache Size = No Caching Cache Utilization = 0.0% (0/512.0M) Shared Memory Utilization = 0.0% (0/512.0M) Types In Cache = com.kabira.snippets.managedobjects.NamedCache$A Flusher Sleep Interval = 1 Maximum Objects Per Flush = 0
Notice that caching has been disabled in the named cache because the cache size was set to zero, and there are no objects in the cache after the snippet completes because the object was flushed from shared memory.