Oracle Application Server Containers for J2EE Services Guide 10g (9.0.4) Part Number B10326-01 |
|
This chapter describes the Oracle Application Server Containers for J2EE (OC4J) Java Object Cache, including its architecture and programming features.
This chapter covers the following topics:
Oracle Application Server 10g offers the Java Object Cache to help e-businesses manage Web site performance issues for dynamically generated content. The Java Object Cache improves the performance, scalability, and availability of Web sites running on Oracle Application Server 10g.
By storing frequently accessed or expensive-to-create objects in memory or on disk, the Java Object Cache eliminates the need to repeatedly create and load information within a Java program. The Java Object Cache retrieves content faster and greatly reduces the load on application servers.
The Oracle Application Server 10g cache architecture includes the following cache components:
The Web Cache is an HTTP-level cache, maintained outside the application, providing fast cache operations. It is a pure, content-based cache, capable of caching static data (such as HTML, GIF, or JPEG files) or dynamic data (such as servlet or JSP results). Given that it exists as a flat content-based cache outside the application, it cannot cache objects (such as Java objects or XML DOM--Document Object Model--objects) in a structured format. In addition, it offers relatively limited postprocessing abilities on cached data.
A custom tag library or API enables you to define page fragment boundaries and to capture, store, reuse, process, and manage the intermediate and partial execution results of JSP pages and servlets as cached objects. Each block can produce its own resulting cache object. The cached objects can be HTML or XML text fragments, XML DOM objects, or Java serializable objects. These objects can be cached conveniently in association with HTTP semantics. Alternatively, they can be reused outside HTTP, such as in outputting cached XML objects through Simple Mail Transfer Protocol (SMTP), Java Message Service (JMS), Advanced Queueing (AQ), or Simple Object Access Protocol (SOAP).
Note: This chapter focuses on the Java Object Cache. For a full discussion of all three caches and their differences, see the Oracle Application Server Containers for J2EE JSP Tag Libraries and Utilities Reference. |
Figure 9-1 shows the basic architecture for the Java Object Cache. The cache delivers information to a user process. The process could be a servlet application that generates HTML pages, or any other Java application.
The Java Object Cache is an in-process, process-wide caching service for general application use. That is, objects are cached within the process memory space and the Java Object Cache is a single service that is shared by all threads running in the process, as opposed to a service that runs in another process. The Java Object Cache can manage any Java object. To facilitate sharing of cached objects, all objects within the cache are accessed by name. The caching service doesn't impose a structure on objects being cached. The name, structure, type and original source of the object are all defined by the application.
To maximize system resources, all objects within the cache are shared. However, access to cached objects is not serialized by access locks, allowing for a high level of concurrent access. When an object is invalidated or updated, the invalid version of the object remains in the cache as long as there are references to that particular version of the object. It is thus possible to have multiple versions of an object in the cache at the same time; however, there is never more than one valid version of the object. The old or invalid versions of an object are visible only to applications that had references to the version before it was invalidated. If an object is updated, a new copy of the object is created in the cache and the old version is marked as invalid.
Objects are loaded into the cache with a user-provided CacheLoader object. This loader object is called by the Java Object Cache when a user application requests an object from the cache and it is not already present. Figure 9-1 is a graphical representation of the architecture. The application interacts with the cache to retrieve objects, the cache interacts via the CacheLoader with the data source. This gives a clean division between object creation and object use.
The Java Object Cache can be used in an environment in which multiple Java processes are running the same application or working on behalf of the same application. In this environment, it is useful to have identical objects cached in different process. For simplicity, availability and performance, the Java Object Cache is specific to each process. There is no centralized control of which objects are loaded into a process. However, the Java Object Cache coordinates object updating and invalidation between processes. If an object is updated or invalidated in one process, it is also updated on invalidated in all other associated processes. This distributed management allows a system of processes to stay synchronized without the overhead of centralized control.
Figure 9-2 is a graphical representation of the following:
The Java Object Cache manages Java objects within a process, across processes, and on a local disk. The Java Object Cache provides a powerful, flexible, and easy-to-use service that significantly improves Java performance by managing local copies of Java objects. There are very few restrictions on the types of Java objects that can be cached or on the original source of the objects. Programmers use the Java Object Cache to manage objects that, without cache access, are expensive to retrieve or to create.
The Java Object Cache is easy to integrate into new and existing applications. Objects can be loaded into the object cache, using a user-defined object, the CacheLoader, and can be accessed through a CacheAccess object. The CacheAccess object supports local and distributed object management. Most of the functionality of the Java Object Cache does not require administration or configuration. Advanced features support configuration using administration APIs in the Cache class. Administration includes setting configuration options, such as naming local disk space or defining network ports. The administration features allow applications to fully integrate the Java Object Cache.
Each cached Java object has a set of associated attributes that control how the object is loaded into the cache, where the object is stored, and how the object is invalidated. Cached objects are invalidated based on time or an explicit request. (Notification can be provided when the object is invalidated.) Objects can be invalidated by group or individually.
Figure 9-3 shows the basic Java Object Cache APIs. Figure 9-3 does not show distributed cache management.
The Java Object Cache is organized as follows:
Table 9-1 contains a summary of the constructs in the cache environment and the cache object types.
The Java Object Cache provides the following features:
This section describes the object types that the Java Object Cache manages, including:
Memory objects are Java objects that the Java Object Cache manages. Memory objects are stored in the Java virtual machine (JVM) heap space as Java objects. Memory objects can hold HTML pages, the results of a database query, or any information that can be stored as a Java object.
Memory objects are usually loaded into the Java Object Cache with an application-supplied loader. The source of the memory object can be external (for example, using data in a table on the Oracle9i Database Server). The application supplied loader accesses the source and either creates or updates the memory object. Without the Java Object Cache, the application would be responsible for accessing the source directly, rather than using the loader.
You can update a memory object by obtaining a private copy of the memory object, applying the changes to the copy, and then placing the updated object back in the cache (using the CacheAccess.replace() method). This replaces the original memory object.
The CacheAccess.defineObject() method associates attributes with an object. If attributes are not defined, then the object inherits the default attributes from its associated region, subregion, or group.
An application can request that a memory object be spooled to a local disk (using the SPOOL attribute). Setting this attribute allows the Java Object Cache to handle memory objects that are large, or costly to re-create and seldom updated. When the disk cache is set up to be significantly larger than the memory cache, objects on disk stay in the disk cache longer than objects in memory.
Combining memory objects that are spooled to a local disk with the distributed feature from the DISTRIBUTE attribute provides object persistence (when the Java Object Cache is running in distributed mode). Object persistence allows objects to survive the restarting of the JVM.
Disk objects are stored on a local disk and are accessed directly from the disk by the application using the Java Object Cache. Disk objects can be shared across Java Object Cache processes, or they can be local to a particular process, depending on disk location specified and the setting for the DISTRIBUTE attribute (and whether the Java Object Cache is running in distributed or local mode).
Disk objects can be invalidated explicitly or by setting the TimeToLive or IdleTime attributes. When the Java Object Cache requires additional space, disk objects that are not being referenced can be removed from the cache.
A StreamAccess object is a special cache object set up to be accessed using the Java InputStream and OutputStream classes. The Java Object Cache determines how to access the StreamAccess object based on the size of the object and the capacity of the cache. Smaller objects are accessed from memory; larger objects are streamed directly from disk. All streamAccess objects are stored on disk.
The cache user's access to the StreamAccess object is through an InputStream. All the attributes that apply to memory objects and disk objects also apply to StreamAccess objects. A StreamAccess object does not supply a mechanism to manage a stream--for example, StreamAccess objects cannot manage socket endpoints. InputStream and OutputStream objects are available to access fixed-sized, potentially large objects.
A pool object is a special class of object that the Java Object Cache manages. A pool object contains a set of identical object instances. The pool object itself is a shared object; the objects within the pool are private objects. Individual objects within the pool can be checked out to be used and then returned to the pool when they are no longer needed.
Attributes, including TimeToLive or IdleTime can be associated with a pool object. These attributes apply to the pool object as a whole.
The Java Object Cache instantiates objects within a pool using an application-defined factory object. The size of a pool decreases or increases based on demand and on the values of the TimeToLive or IdleTime attributes. A minimum size for the pool is specified when the pool is created. The minimum size value is interpreted as a request rather than a guaranteed minimum value. Objects within a pool object are subject to removal from the cache due to lack of space, so the pool can decrease below the requested minimum value. A maximum pool size value can be set by putting a hard limit on the number of objects available in the pool.
The Java Object Cache environment includes the following:
This section describes these Java Object Cache environment constructs.
The Java Object Cache manages objects within a cache region. A cache region defines a name space within the cache. Each object within a cache region must be uniquely named, and the combination of the cache region name and the object name must uniquely identify an object. Thus, cache region names must be unique from other region names, and all objects within a region must be uniquely named relative to the region. (Multiple objects can have the same name if they are within different regions or subregions.)
You can define as many regions as you need to support your application. However, most applications require only one region. The Java Object Cache provides a default region; when a region is not specified, objects are placed in the default region.
Attributes can be defined for a region and are then inherited by the objects, subregions, and groups within the region.
The Java Object Cache manages objects within a cache region. Specifying a subregion within a cache region defines a child hierarchy. A cache subregion defines a name space within a cache region or within a higher cache subregion. Each object within a cache subregion must be uniquely named, and the combination of the cache region name, the cache subregion name, and the object name must uniquely identify an object.
You can define as many subregions as you need to support your application.
A subregion inherits its attributes from its parent region or subregion unless the attributes are defined when the subregion is defined. A subregion's attributes are inherited by the objects within the subregion. If a subregion's parent region is invalidated or destroyed, the subregion is also invalidated or destroyed.
A cache group creates an association between objects within a region. Cache groups allow related objects to be manipulated together. Objects are typically associated in a cache group because they need to be invalidated together or they use common attributes. Any set of cache objects within the same region or subregion can be associated using a cache group, which can, in turn, include other cache groups.
A Java Object Cache object can belong to only one group at any given time. Before an object can be associated with a group, the group must be explicitly created. A group is defined with a name. A group can have its own attributes, or it can inherit its attributes from its parent region, subregion, or group.
Group names are not used to identify individual objects. A group defines a set or collection of objects that have something in common. A group does not define a hierarchical name space. Object type does not distinguish objects for naming purposes; therefore, a region cannot include a group and a memory object with the same name. Use subregions to define a hierarchical name space within a region.
Groups can contain groups, with the groups having a parent and child relationship. The child group inherits attributes from the parent group.
With the 10g (9.0.4) version of the Java Object Cache, the maximum size of a region or group can be specified as either the number of objects in the region or group or the maximum number of bytes allowed. If the number of bytes controls the region capacity, then set the size attribute for all objects in the region. This can be set either directly by the user when the object is created, or automatically by setting the Attributes.MEASURE attribute flag. The size of a region or group can be set at multiple levels in the naming hierarchy--that is, at the region and subregion level or at the group level within a region or another group.
When the capacity of a region or group is reached, the CapacityPolicy object associated with that region or group, if defined, is called. If no capacity policy has been specified, the default policy is used. The default policy follows: If a nonreferenced object of lesser or equal priority is found, it is invalidated in favor of the new object. If the priority attribute has not been set for an object, the priority is assumed to be Integer.MAX_VALUE. When searching for an object to remove, all objects in the immediate region or group and all subregions and subgroups are searched. The first object that can be removed, based on the capacity policy, is removed. So, for example, this may not be the object of lowest priority in the search area.
Figure 9-4 and Figure 9-5 give examples. In each illustration, the grayed portions indicate the search area.
The capacity of region A is set to 50 objects, with subregion B and subregion C set to 30 objects each. If the object count of region A reaches 50, with 10 directly in region A and 20 each in subregions B and C, the capacity policy for region A is called. The object that is removed can come from region A or from one of its subregions. Figure 9-4 shows this situation.
If subregion B reaches 30 before the capacity of region A is reached, the capacity policy for subregion B is called and only objects within subregion B are considered for removal. Figure 9-5 shows this situation.
Cache object attributes affect how the Java Object Cache manages objects. Each object, region, subregion, and group has a set of associated attributes. An object's applicable attributes contain either the default attribute values; the attribute values inherited from the object's parent region, subregion, or group; or the attribute values that you select for the object.
Attributes fall into two categories:
The attributes shown in Table 9-2 must be defined for an object before the object is loaded. These attributes determine an object's basic management characteristics.
The following list shows the methods that you can use to set the attributes shown in Table 9-2 (by setting the values of an Attributes object argument).
CacheAccess.defineRegion()
CacheAccess.defineSubRegion()
CacheAccess.defineGroup()
CacheAccess.defineObject()
CacheAccess.put()
CacheAccess.createPool()
CacheLoader.createDiskObject()
CacheLoader.createStream()
CacheLoader.SetAttributes()
You cannot reset the attributes shown in Table 9-2 by using the CacheAccess.resetAttributes()method.
Note:
Table 9-2 Java Object Cache Attributes-Set at Object Creation
A set of Java Object Cache attributes can be modified either before or after object loading. Table 9-3 lists these attributes. These attributes can be set using the methods in the list under "Using Attributes Defined Before Object Loading", and can be reset using the CacheAccess.resetAttributes() method.
This section describes how to develop applications that use the Java Object Cache. This section covers the following topics:
The Oracle installer installs the Java Object Cache JAR file cache.jar in the directory $ORACLE_HOME/javacache/lib on UNIX or in %ORACLE_HOME%\javacache\lib on Windows.
To use the Java Object Cache, import oracle.ias.cache, as follows:
import oracle.ias.cache.*;
All access to the Java Object Cache is through a CacheAccess object. A CacheAccess object is associated with a cache region. You define a cache region, usually associated with the name of an application, using the CacheAccess.defineRegion()static method. If the cache has not been initialized, then defineRegion() initializes the Java Object Cache.
When you define the region, you can also set attributes. Attributes specify how the Java Object Cache manages objects. The Attributes.setLoader() method sets the name of a cache loader. Example 9-1 shows this.
Attributes attr = new Attributes(); MyLoader mloader = new MyLoader; attr.setLoader(mloader); attr.setDefaultTimeToLive(10); final static String APP_NAME_ = "Test Application"; CacheAccess.defineRegion(APP_NAME_, attr);
The first argument for defineRegion uses a String to set the region name. This static method creates a private region name within the Java Object Cache. The second argument defines the attributes for the new region.
Create a cache group when you want to create an association between two or more objects within the cache. Objects are typically associated in a cache group because they must be invalidated together or because they have a common set of attributes.
Any set of cache objects within the same region or subregion can be associated using a cache group, including other cache groups. Before an object can be associated with a cache group, the cache group must be defined. A cache group is defined with a name and can use its own attributes, or it can inherit attributes from its parent cache group, subregion, or region. The code in Example 9-2 defines a cache group within the region named Test Application:
final static String APP_NAME_ = "Test Application"; final static String GROUP_NAME_ = "Test Group"; // obtain an instance of CacheAccess object to a named region CacheAccess caccess = CacheAccess.getAccess(APP_NAME_); // Create a group caccess.defineGroup(GROUP_NAME_); // Close the CacheAccess object caccess.close();
Define a subregion when you want to create a private name space within a region or within a previously defined subregion. The name space of a subregion is independent of the parent name space. A region can contain two objects with the same name, as long as the objects are within different subregions.
A subregion can contain anything that a region can contain, including cache objects, groups, or additional subregions. Before an object can be associated with a subregion, the subregion must be defined. A cache subregion is defined with a name and can use its own attributes, or it can inherit attributes from its parent cache region or subregion. Use the getParent() method to obtain the parent of a subregion.
The code in Example 9-3 defines a cache subregion within the region named Test Application.
final static String APP_NAME_ = "Test Application"; final static String SUBREGION_NAME_ = "Test SubRegion"; // obtain an instance of CacheAccess object to a named region CacheAccess caccess = CacheAccess.getAccess(APP_NAME_); // Create a SubRegion caccess.defineSubRegion(SUBREGION_NAME_); // Close the CacheAccess object caccess.close();
You may sometimes want to describe to the Java Object Cache how an individual object should be managed within the cache before the object is loaded. You can specify management options when the object is loaded, by setting attributes within the CacheLoader.load() method. However, you can also associate attributes with an object by using the CacheAccess.defineObject() method. If attributes are not defined for an object, then the Java Object Cache uses the default attributes set for the region, subregion, or group with which the object is associated.
Example 9-4 shows how to set attributes for a cache object. The example assumes the region APP_NAME_ has already been defined.
import oracle.ias.cache.*; final static String APP_NAME_ = "Test Application"; CacheAccess cacc = null; try { cacc = CacheAccess.getAccess(APP_NAME_); // set the default IdleTime for an object using attributes Attributes attr = new Attributes(); // set IdleTime to 2 minutes attr.setIdleTime(120); // define an object and set its attributes cacc.defineObject("Test Object", attr); // object is loaded using the loader previously defined on the region // if not already in the cache. result = (String)cacc.get("Test Object"); } catch (CacheException ex){ // handle exception } finally { if (cacc!= null) cacc.close(); }
The Java Object Cache has two mechanisms for loading an object into the cache. The object can be put into the cache directly by the application using the CacheAccess.put() method or you can implement a CacheLoader object. In most cases, implementing the CacheLoader is the preferred method. With a cache loader, the Java Object Cache automatically determines if an object needs to be loaded into the cache when the object is request. And the Java Object Cache coordinates the load if multiple users request the object at the same time.
A CacheLoader object can be associated with a region, subregion, group, or object. Using a CacheLoader allows the Java Object Cache to schedule and manage object loading and handle the logic for "if the object is not in cache then load."
If an object is not in the cache, then when an application calls the CacheAccess.get() or CacheAccess.preLoad() method, the cache executes the CacheLoader.load method. When the load method returns, the Java Object Cache inserts the returned object into the cache. Using CacheAccess.get(), if the cache is full, the object is returned from the loader and the object is immediately invalidated in the cache. (Therefore, using the CacheAccess.get() method with a full cache does not generate a CacheFullException.)
When a CacheLoader is defined for a region, subregion, or group, it is taken to be the default loader for all objects associated with the region, subregion, or group. A CacheLoader object that is defined for an individual object is used only to load the object.
The CacheLoader cache provides several helper methods that you can use from within the load() method implementation. Table 9-4 summarizes the available CacheLoader methods.
Example 9-5 shows a CacheLoader object using the cacheLoader.netSearch() method to check if the object being loaded is available in distributed Java Object Cache caches. If the object is not found using netSearch(), then the load method uses a more expensive call to retrieve the object. (An expensive call might involve an HTTP connection to a remote Web site or a connection to the Oracle9i Database Server.) For this example, the Java Object Cache stores the result as a String.
import oracle.ias.cache.*; class YourObjectLoader extends CacheLoader{ public YourObjectLoader () { } public Object load(Object handle, Object args) throws CacheException { String contents; // check if this object is loaded in another cache try { contents = (String)netSearch(handle, 5000);// wait for up to 5 scnds return new String(contents); } catch(ObjectNotFoundException ex){} try { contents = expensiveCall(args); return new String(contents); } catch (Exception ex) {throw exceptionHandler("Loadfailed", ex);} } private String expensiveCall(Object args) { String str = null; // your implementation to retrieve the information. // str = ... return str; } }
An object can be removed from the cache either by setting the TimeToLive attribute for the object, group, subregion, or region or by explicitly invalidating or destroying the object.
Invalidating an object marks the object for removal from the cache. Invalidating a region, subregion, or group invalidates all the individual objects from the region, subregion, or group, leaving the environment--including all groups, loaders, and attributes--available in the cache. Invalidating an object does not undefine the object. The object loader remains associated with the name. To completely remove an object from the cache, use the CacheAccess.destroy() method.
An object can be invalidated automatically based on the TimeToLive or IdleTime attribute. When the TimeToLive or IdleTime expires, objects are, by default, invalidated and not destroyed.
If an object, group, subregion, or region is defined as distributed, the invalidate request is propagated to all caches in the distributed environment.
To invalidate an object, group, subregion, or region, use the CacheAccess.invalidate() method as follows:
CacheAccess cacc = CacheAccess.getAccess("Test Application"); cacc.invalidate("Test Object"); // invalidate an individual object cacc.invalidate("Test Group"); // invalidate all objects associated with a group cacc.invalidate(); // invalidate all objects associated with the region cacc cacc.close(); // close the CacheAccess handle
An object can be removed from the cache either by setting the TimeToLive attribute for the object, group, subregion, or region or by explicitly invalidating or destroying the object.
Destroying an object marks the object and the associated environment, including any associated loaders, event handlers, and attributes for removal from the cache. Destroying a region, subregion, or a group marks all objects associated with the region, subregion, or group for removal, including the associated environment.
An object can be destroyed automatically based on the TimeToLive or IdleTime attributes. By default, objects are invalidated and are not destroyed. If the objects must be destroyed, set the attribute GROUP_TTL_DESTROY. Destroying a region also closes the CacheAccess object used to access the region.
To destroy an object, group, subregion, or region, use the CacheAccess.destroy() method as follows:
CacheAccess cacc = CacheAccess.getAccess("Test Application"); cacc.destroy("Test Object"); // destroy an individual object cacc.destroy("Test Group"); // destroy all objects associated with // the group "Test Group" cacc.destroy(); // destroy all objects associated with the region // including groups and loaders
In most cases, objects are loaded into the cache individually; in some cases, however, multiple objects can be loaded into the cache as a set. The primary example of this is when multiple cached objects can be created from a single read from a database. In this case, it is much more efficient to create multiple objects from a single call to the CacheLoader.load method.
To support this scenario, the abstract class CacheListLoader and the method CacheAccess.loadList have been added. The CacheListLoader object extends the CacheLoader object defining the abstract method loadList and the helper methods getNextObject, getList, getNamedObject, and saveObject. The cache user implements the CacheListLoader.loadList method. Employing the helper methods, the user can iterate through the list of objects, creating each one and saving it to the cache. If the helper methods defined in CacheLoader are used from the CacheListLoader method, getNextObject or getNamedObject should be called first to set the correct context.
The CacheAccess.loadList method takes as an argument an array of object names to be loaded. The cache processes this array of objects. Any objects that are not currently in the cache are added to a list that is passed to the CacheListLoader object that is defined for the cached objects. If a CacheListLoader object is not defined for the objects or the objects have different CacheListLoader objects defined, then each object is loaded individually using the CacheLoader.load method defined.
It is always best to implement both the CacheListLoader.loadList method and the CacheListLoader.load method. Which method is called depends on the order of the user requests to the cache. For example, if the CacheAccess.get method is called before the CacheAccess.loadList method, the CacheListLoader.load method is used rather than the CacheAccess.loadList method.
As a convenience, the invalidate and destroy methods have been overloaded to also handle an array of objects.
Example 9-6 shows a sample CacheListLoader and Example 9-7 shows sample usage.
Public class ListLoader extends CacheListLoader { public void loadList(Object handle, Object args) throws CacheException { while(getNextObject(handle) != null) { // create the cached object based on the name of the object Object cacheObject = myCreateObject(getName(handle)); saveObject(handle, cacheObject); } } public Object load(Object handle, Object args) throws CacheException { return myCreateObject(getName(handle)); } private Object myCreateObject(Object name) { // do whatever to create the object } }
// Assumes the cache has already been initialized CacheAccess cacc; Attributes attr; ListLoader loader = new ListLoader(); String objList[]; Object obj; // set the CacheListLoader for the region attr = new Attributes(); attr.setLoader(loader); //define the region and get access to the cache CacheAccess.defineRegion("region name", attr); cacc = CacheAccess.getAccess("region name"); // create the array of object names objList = new String[3]; for (int j = 0; j < 3; j++) objList[j] = "object " + j; // load the objects in the cache via the CacheListLoader.loadList method cacc.loadList(objList); // retrieve the already loaded object from the cache obj = cacc.get(objList[0]); // do something useful with the object // load an object using the CacheListLoader.load method obj = cache.get("another object") // do something useful with the object
By default, the Java Object Cache is initialized automatically upon OC4J startup. The OC4J runtime automatically initializes the Java Object Cache using configuration settings defined in the file javacache.xml. The file path is specified in the <javacache-config> tag of the OC4J server.xml file. The default relative path values of javacache.xml in server.xml are the following:
<javacache-config path="../../../javacache/admin/javacache.xml"/>
The rules for writing javacache.xml and the default configuration values are specified in an XML schema. The XML schema file ora-cache.xsd and the default javacache.xml are in the directory $ORACLE_HOME/javacache/admin on UNIX and in %ORACLE_HOME%\javacache\admin on Windows.
In previous versions of Java Object Cache, configuration was done through the file javacache.properties; the 10g (9.0.4) release uses javacache.xml.
A sample configuration follows:
<?xml version="1.0" encoding="UTF-8"?> <cache-configuration xmlns=http://www.oracle.com/oracle/ias/cache/configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/oracle/ias/cache/configuration ora-cache.xsd"> <logging> <location>javacache.log</location> <level>ERROR</level> </logging> <communication> <isDistributed>true</isDistributed> <coordinator discovery-port="7000"/> </communication> <persistence> <location>diskcache</location> <disksize>32</disksize> </persistence> <max-objects>1000</max-objects> <max-size>48</max-size> <clean-interval>30</clean-interval> </cache-configuration>
Table 9-5 contains the valid property names and the valid types for each property.
Configuration XML Element | Description | Type |
---|---|---|
|
Specifies the time, in seconds, between each cache cleaning. At the cache-cleaning interval, the Java Object Cache checks for objects that have been invalidated by the TimeToLive or IdleTime attributes that are associated with the object. (Table 9-3 describes these attributes are described.) Default value: 60 |
positive integer |
|
Specifies the time, in seconds, between each cache death detection for determining the availability of the remote cache systems. Default value: 60 |
positive integer |
|
Specifies the maximum size of the memory, in megabytes, available to the Java Object Cache. Default value: 10 |
positive integer |
|
Specifies the maximum number of in-memory objects that are allowed in the cache. The count does not include group objects or objects that have been spooled to disk and are not currently in memory. Default value: 5000 |
positive integer |
|
Specifies the separator between a parent region and a child region name. See "Examples". Default value: / |
|
|
Specifies the full path to the declarative cache configuration file. The format of the file must conform to the declarative cache schema (cache.xsd). The declarative cache configuration allows the system to predefine cache regions, groups, objects, attributes, and policies upon Java Object Cache service initialization. For more information about the declarative cache, see "Declarative Cache". Also see "Examples". Default value: Not use a declarative cache. |
|
|
Indicates whether the cache is distributed. Specifies the IP address and port that the Java Object Cache initially contacts to join the caching system, when using distributed caching. Updates and invalidation for objects that have the distribute property set are propagated to other caches known to the Java Object Cache. If the isDistributed subelement of the communication element is set to false, all objects are treated as local, even when the attributes set on objects are set to distribute. See "Examples". Default value: Cache is not distributed (isDistributed subelement set to false). |
complex (has subelements) |
|
Specifies the logger attributes such as log file name and log level. The available options of the log level are OFF, FATAL, ERROR, DEFAULT, WARNING, TRACE, INFO, and DEBUG. See "Examples".
Default values: |
complex (has subelements) |
|
Specifies the disk cache configuration, such as absolute path to the disk cache root and maximum size for the disk cache. If a root path is specified, the default maximum size of the disk cache is 10MB. The unit of the disk cache size is megabytes. See "Examples". Default value: Disk caching is not available. |
complex (has subelements) |
The following example shows the use of the <region-name-separator> element:
The following example shows the use of the <preload-file> element:
<preload-file>/app/oracle/javacache/admin/decl.xml</preload-file>
The following examples show the use of the <communication> element:
<communication> <isDistributed>false</isDistributed> </communication>
<communication> <isDistributed>true</isDistributed> </communication>
<communication> <isDistributed>true</isDistributed> <coordinator discovery-port="7000"> </communication>
<communication> <isDistributed>true</isDistributed> <coordinator ip="192.10.10.10" discovery-port="7000"> </communication>
<communication> <isDistributed>true</isDistributed> <coordinator ip="192.10.10.10" discovery-port="7000"> <coordinator ip="192.11.11.11" discovery-port="7000"> <coordinator ip="192.22.22.22" discovery-port="7000"> <coordinator ip="192.22.22.22" discovery-port="8000"> </communication>
The following examples show the use of the <persistence> element:
<persistence> <location>/app/9iAS/javacache/admin/diskcache</location> </persistence>
<persistence> <location>/app/9iAS/javacache/admin/diskcache</location> <disksize>20</disksize> </persistence>
The following examples show the use of the <logging> element:
<logging> <location>/app/9iAS/javacache/admin/logs/my_javacache.log</location> </logging>
<logging> <location>/app/9iAS/javacache/admin/logs/my_javacache.log</location> <level>INFO</level> </logging>
With the 10g (9.0.4) release of the Java Object Cache, object, group, and region, as well as cache attributes, can be defined declaratively. You do not need to write any Java code to define cache objects and attributes in your applications when using declarative cache.
A declarative cache file can be read automatically during Java Object Cache initialization. Specify the location of the declarative cache file in the <preload-file> element of the cache configuration file. (See "Sharing Cached Objects in an OC4J Servlet" for cache configuration file syntax.) In addition, the declarative cache file can be loaded programmatically or explicitly with the public methods in oracle.ias.cache.Configurator.class. Multiple declarative cache files are also permitted.
Figure 9-6 shows the declarative cache.
You can set up the Java Object Cache for automatically loading a declarative cache file during system initialization. Example 9-8 shows this. Example 9-9 shows how to programmatically read the declarative cache file.
<!-- Specify declarative cache file:my_decl.xml in javacache.xml --> <cache-configuration> ... <preload-file>/app/9iAS/javacache/admin/my_decl.xml</preload-file> ... </cache-configuration>
try { String filename = "/app/9iAS/javacache/admin/my_decl.xml"; Configurator config = new Configurator(filename); Config.defineDeclarable(); } catch (Exception ex) { }
<?xml version="1.0" encoding="UTF-8"?> <cache xmlns="http://www.javasoft.com/javax/cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/javax/cache"> <region name="fruit"> <attributes> <time-to-live>3000</time-to-live> <max-count>200</max-count> <capacity-policy> <classname>com.acme.MyPolicy</classname> </capacity-policy> </attributes> <group name="apple"> <attributes> <flag>spool</flag> <flag>distribute</flag> <cache-loader> <classname>com.acme.MyLoader</classname> <parameter name="color">red</parameter> </cache-loader> </attributes> </group> <cached-object> <name> <string-name>theme</string-name> </name> <object> <classname>com.acme.DialogHandler</classname> <parameter name="prompt">Welcome</parameter> </object> </cached-object> </region> </cache>
The declarative cache file is in XML format. The file contents should conform to the declarative cache XML schema that is shipped with Oracle Application Server 10g. The file path of the XML schema is ORACLE_HOME
/javacache/admin/cache.xsd.
Table 9-6 lists the elements of the declarative cache schema, their children, and the valid types for each element. See "Examples" for code that shows usage for most elements.
Figure 9-7 shows the attributes of the declarative cache schema.
The following examples show use of elements in Table 9-6:
<region name="themes"> <region name="cartoon"> <!-- sub region definition --> </region> <group name="colors"> <!-- group definition --> </group> </region>
<group name="colors"> <group name="dark"> <!-- sub group definition --> </group> </group>
<cached-object> <name> <string-name>DialogHandler</string-name> </name> <object> <classname>com.acme.ConfigManager</classname> <parameter name="color">blue</parameter> </object> </cached-object>
<name> <string-name>DialogHandler</string-name> </name>
Declare the name for a cached object with the <name> element using an object:
<name> <object-name> <classname>DialogHandler</classname> <parameter name="color">green</parameter> </object-name> </name>
<object> <classname>com.acme.CustomConfigManager</classname> <parameter name="color">blue</parameter> </object> // Implementation of CustomConfigManager.java package com.acme; import oracle.ias.cache.Declarable; public class CustomConfigManager implements Declarable { }
<attributes> <time-to-live>4500</time-to-live> <default-ttl>6000</default-ttl> <version>99</version> <max-count>8000</max-count> <priority>50</priority> <flag>spool</flag> <flag>allownull</flag> <flag>distribute</flag> <flag>reply</flag> <cache-loader> <classname>MyLoader</classname> <parameter name="debug">false</parameter> </cache-loader> </attributes>
<attributes> <user-defined> <key>color</key> <value>red</value> </user-defined> </attributes>
The topology of the cache objects, object attributes, and user-defined objects can all be described in the declarative cache file. For the system to load and instantiate a user-defined Java object (including CacheLoader, CacheEventListener, and CapacityPolicy) declared in the declarative cache file, such object must be an instance of the oracle.ias.cache.Declarable interface. That is, you must implement the oracle.ias.cache.Declarable interface for any Java objects declared in the declarative cache file. You must be aware that all user-defined Java objects are loaded by the JVM's default class loader instead of the application's class loaders. After the declarable object is instantiated, the system implicitly invokes its init(Properties props) method. The method uses the user-supplied parameters (name-value pair) defined in the declarative cache file to perform any necessary initialization task. Example 9-10 shows how to define an object by declaratively passing in a parameter (color = yellow).
In the declarative XML file:
<cached-object> <name> <string-name>Foo</string-name> </name> <object> <classname>com.acme.MyCacheObject</classname> <parameter name="color">yellow</parameter> </object> </cached-object>
Declarable object implementation:
package com.acme; import oracle.ias.cache.*; import java.util.Properties; public class MyCacheObject implements Declarable { private String color_; /** * Object initialization */ public void init(Properties prop) { color_ = prop.getProperty("color"); } }
When you specify a CacheLoader, CacheEventListener, or CapacityPolicy object in the declarative cache file, the object itself must also be an instance of oracle.ias.cache.Declarable. This requirement is similar to that of the user-defined object. You must implement a declarable interface for each specified object in addition to extending the required abstract class. Example 9-11 shows a declarable CacheLoader implementation.
import oracle.ias.cache.*; import java.util.Properties; public class MyCacheLoader extends CacheLoader implements Declarable { public Object load(Object handle, Object argument) { // should return meaningful object based on argument return null; } public void init(Properties prop) { } }
To use the Java Object Cache in any Java application but run it in a non-OC4J runtime, insert the following reference to where the application (Java class) is initialized:
Cache.open(/path-to-ocnfig-file
/javacache.xml);
If you invoke Cache.open() without any parameter in your code, then the Java Object Cache uses its internal default configuration parameter. You can also initialize the Java Object Cache by invoking Cache.init(CacheAttributes). This allows you to derive the configuration parameters from your own configuration file or generate them programmatically.
If the Java Object Cache is not used in the OC4J runtime, you must include cache.jar in the classpath where the JVM is launched. You must also initialize the Java Object Cache explicitly by invoking Cache.open(String config_filename
), where config_filename
is the full path to a valid javacache.xml file, or by invoking Cache.init(CacheAttributes)
.
Use any of the following method invocations to initialize the Java Object Cache explicitly in a non-OC4J container:
Cache.open();
Use the default Java Object Cache configuration stored in cache.jar
Cache.open(/
path-to-oracle-home/javacache/admin/javacache.xml
);
Use the configuration defined in the javacache.xml file
Cache.open(/
path-to-user's-own-javacache.xml
);
Use the configuration defined in the specific javacache.xml
Cache.init(CacheAttributes);
Use the configuration that is set in a CacheAttributes object
For J2EE applications running in an OC4J container, the path to the javacache.xml
file can be configured in the OC4J server.xml
configuration file. The cache can be initialized automatically when the OC4J process is started. See OC4J configuration for details.
In a non-OC4J container, if you do not use any of the preceding method invocations, the Java Object Cache is initialized implicitly (using default configuration settings stored in cache.jar) when you invoke Cache.getAccess() or Cache.defineRegion().
The new capacity control feature allows the cache user to specify the policy to employ when determining which objects should be removed from the cache when the capacity of the cache, region, or group has been reached. To specify the policy, extend the abstract class CapacityPolicy and set the instantiated object as an attribute of the cache, region, or group.
For regions and groups, the CapacityPolicy object is called when the region or group has reached its capacity and a new object is being loaded. An object in the region or group must be found to invalidate, or the new object is not saved in the cache. (It is returned to the user but is immediately invalidated.)
The CapacityPolicy object that is associated with the cache as a whole is called when capacity of the cache reaches some "high water mark," some percentage of the configured maximum. When the high water mark is reach, the cache attempts to remove objects to reduce the load in the cache to 3% below the high water mark. The high water mark is specified by the capacityBuffer cache attribute. If the capacityBuffer is set to 5, then the cache begins removing objects from the cache when it is 95% full (100% -5%) and continues until the cache is 92% full (95% - 3%). The default value for capacityBuffer is 15.
The capacity policy used for the cache can be different from those used for specific regions or groups.
By default, the capacity policy for groups and regions is to remove a nonreferenced object of equal or lesser priority when a new object is added and capacity has been reached. For the cache, the default policy is to remove objects that have not been referenced in the last two clean intervals with preference to objects of priority--that is, low priority objects that have not been referenced recently are removed first.
To help create a capacity policy, many statistics are kept for objects in the cache and aggregated across the cache, regions, and groups. The statistics are available to the CapacityPolicy object. For cache objects, the following statistics are maintained:
Along with these statistics, all attributes associated with the object are available to the CapacityPolicy object.
The following aggregated statistics are maintained for the cache, regions, and groups. For each of these statistics, the low, high and average value is maintained. These statistics are recalculated at each clean interval or when Cache.updateStats() is called.
Example 9-12 is a sample CapacityPolicy object for a region, based on object size.
class SizePolicy extends CapacityPolicy { public boolean policy (Object victimHandle, AggregateStatus aggStatus,
long currentTime , Object newObjectHandle) throws CacheException { int newSize; int oldSize; oldSize = getAttributes(victimHandle).getSize(); newSize = getAttributes(newObjectHandle).getSize(); if (newSize >= oldSize) return true; return false; }
Example 9-13 is a sample CapacityPolicy for the cache based, on access time and reference count. If an object has below-average references and has not been accessed in the last 30 seconds, then it is removed from the cache.
class SizePolicy extends CapacityPolicy { public boolean policy (Object victimHandle, AggregateStatus aggStatus, long
currentTime , Object newObjectHandle) throws CacheException { long lastAccess; int accessCount; int avgAccCnt; lastAccess = getStatus(victimHandle).getLastAccess(); accessCount = getStatus(victimHandle).getAccessCount(); avgAccCnt = aggStatus.getAccessCount(AggregateStatus.AVG); if (lastAccess + 30000 < currentTime && accessCount < avgAccCnt) return true; } }
Many events can occur in the life cycle of a cached object, including object creation and object invalidation. This section shows how an application can be notified when cache events occur.
To receive notification of the creation of an object, implement event notification as part of the cacheLoader. For notification of invalidation or updates, implement a CacheEventListener, and associate the CacheEventListener with an object, group, region, or subregion using Attributes.setCacheEventListener().
CacheEventListener is an interface that extends java.util.EventListener. The cache event listener provides a mechanism to establish a callback method that is registered and then executes when the event occurs. In the Java Object Cache, the event listener executes when a cached object is invalidated or updated.
An event listener is associated with a cached object, group, region, or subregion. If an event listener is associated with a group, region, or subregion, by default, the listener runs only when the group, region, or subregion itself is invalidated. Invalidating a member does not trigger the event. The Attributes.setCacheEventListener() call takes a boolean argument that, if true, applies the event listener to each member of the region, subregion, or group, rather than to the region, subregion, or group itself. In this case, the invalidation of an object within the region, subregion, or group triggers the event.
The CacheEventListener interface has one method, handleEvent(). This method takes a single argument, a CacheEvent object that extends java.util.EventObject. This object has two methods, getID(), which returns the type of event (OBJECT_INVALIDATION or OBJECT_UPDATED), and getSource(), which returns the object being invalidated. For groups and regions, the getSource() method returns the name of the group or region.
The handleEvent() method is executed in the context of a background thread that the Java Object Cache manages. Avoid using Java Native Interface (JNI) code in this method, as the expected thread context may not be available.
Example 9-14 illustrates how a CacheEventListener is implemented and associated with an object or a group.
import oracle.ias.cache.*; // A CacheEventListener for a cache object class MyEventListener implements CacheEventListener { public void handleEvent(CacheEvent ev) { MyObject obj = (MyObject)ev.getSource(); obj.cleanup(); } // A CacheEventListener for a group object class MyGroupEventListener implements CacheEventListener { public void handleEvent(CacheEvent ev) { String groupName = (String)ev.getSource(); app.notify("group " + groupName + " has been invalidated"); } }
Use the Attributes.listener attribute to specify the CacheEventListener for a region, subregion, group, or object.
Example 9-15 illustrates how to set a cache event listener on an object. Example 9-16 illustrates how to set a cache event listener on a group.
import oracle.ias.cache.*; class YourObjectLoader extends CacheLoader { public YourObjectLoader () { } public Object load(Object handle, Object args) { Object obj = null; Attributes attr = new Attributes(); MyEventListener el = new MyEventListener(); attr.setCacheEventListener(CacheEvent.OBJECT_INVALIDATED, el); // your implementation to retrieve or create your object setAttributes(handle, attr); return obj; } }
import oracle.ias.cache.*; try { CacheAccess cacc = CacheAccess.getAccess(myRegion); Attributes attr = new Attributes (); MyGroupEventListener listener = new MyGroupEventListener(); attr.setCacheEventListener(CacheEvent.OBJECT_INVALIDATED, listener); cacc.defineGroup("myGroup", attr); //.... cacc.close(); }catch(CacheException ex) { // handle exception }
This section covers restrictions and programming pointers to keep in mind when using the Java Object Cache.
The Java Object Cache can manage objects on disk as well as in memory.
This section covers the following topics:
This section covers the following topics:
When operating in local mode, the cache attribute isDistributed is not set and all objects are treated as local objects (even when the DISTRIBUTE attribute is set for an object). In local mode, all objects in the disk cache are visible only to the Java Object Cache cache that loaded them, and they do not survive after process termination. In local mode, objects stored in the disk cache are lost when the process using the cache terminates.
If the cache attribute isDistributed is set to true, the cache will operate in distributed mode. Disk cache objects can be shared by all caches that have access to the file system hosting the disk cache. This is determined by the disk cache location configured. This configuration allows for better utilization of disk resources and allows disk objects to persist beyond the life of the Java Object Cache process.
Objects that are stored in the disk cache are identified using the concatenation of the path that is specified in the diskPath configuration property and an internally generated String representing the remaining path to the file. Thus, caches that share a disk cache can have a different directory structure, as long as the diskPath represents the same directory on the physical disk and is accessible to the Java Object Cache processes.
If a memory object that is saved to disk is also distributed, the memory object can survive the death of the process that spooled it.
There are several ways to use the disk cache with the Java Object Cache, including:
The Java Object Cache automatically adds certain objects to the disk cache. Such objects can reside either in the memory cache or in the disk cache. If an object in the disk cache is needed, it is copied back to the memory cache. The action of spooling to disk occurs when the Java Object Cache determines that it requires free space in the memory cache. Spooling of an object occurs only if the SPOOL attribute is set for the object.
In some situations, you may want to force one or more objects to be written to the Java Object Cache disk cache. Using the CacheAccess.save() method, a region, subregion, group, or object is written to the disk cache. (If the object or objects are already in the disk cache, they are not written again.)
Calling CacheAccess.save() on a region, subregion, or group saves all the objects within the region, subregion, or group to the disk cache. During a CacheAccess.save() method call, if an object is encountered that cannot be written to disk, either because it is not serializable or for other reasons, then the event is recorded in the Java Object Cache log and the save operation continues with the next object. When individual objects are written to disk, the write is synchronous. If a group or region is saved, the write is done as an asynchronous background task.
Objects that you access only directly from disk cache are loaded into the disk cache by calling CacheLoader.createDiskObject() from the CacheLoader.load() method. The createDiskObject() method returns a File object that the application can use to load the disk object. If the attributes of the disk object are not defined for the disk object, then set them using the createDiskObject() method. The system manages local and distributed disk objects differently; the system determines if the object is local or distributed when it creates the object, based on the specified attributes.
When CacheAccess.get() is called on a disk object, the full path name to the file is returned, and the application can open the file, as needed.
Disk objects are stored on a local disk and accessed directly from the disk by the application using the Java Object Cache. Disk objects can be shared by all Java Object Cache processes, or they can be local to a particular process, depending on the setting for the DISTRIBUTE attribute (and the mode the Java Object Cache is running in, either distributed or local).
Example 9-17 shows a loader object that loads a disk object into the cache.
import oracle.ias.cache.*; class YourObjectLoader extends CacheLoader { public Object load(Object handle, Object args) { File file; FileOutputStream = out; Attributes attr = new Attributes(); attr.setFlags(Attributes.DISTRIBUTE); try // The distribute attribute must be set on the createDiskObject method { file = createDiskObject(handle, attr); out = new FileOutputStream(file); out.write((byte[])getInfofromsomewhere()); out.close(); } catch (Exception ex) { // translate exception to CacheException, and log exception throw exceptionHandler("exception in file handling", ex) } return file; } }
Example 9-18 illustrates application code that uses a Java Object Cache disk object. This example assumes that the region named Stock-Market is already defined with the YourObjectLoader loader that was set up in Example 9-17 as the default loader for the region.
import oracle.ias.cache.*; try { FileInputStream in; File file; String filePath; CacheAccess cacc = CacheAccess.getAccess("Stock-Market"); filePath = (String)cacc.get("file object"); file = new File(filePath); in = new FileInputStream(filePath); in.read(buf); // do something interesting with the data in.close(); cacc.close(); } catch (Exception ex) { // handle exception }
A StreamAccess object is accessed as a stream and automatically loaded to the disk cache. The object is loaded as an OutputStream and read as an InputStream. Smaller StreamAccess objects can be accessed from memory or from the disk cache; larger StreamAccess objects are streamed directly from disk. The Java Object Cache automatically determines where to access the StreamAccess object based on the size of the object and the capacity of the cache.
The user is always presented with a stream object, an InputStream for reading and an OutputStream for writing, regardless of whether the object is in a file or in memory. The StreamAccess object allows the Java Object Cache user to always access the object in a uniform manner, without regard to object size or resource availability.
To create a StreamAccess object, call the CacheLoader.createStream() method from the CacheLoader.load() method when the object is loaded into the cache. The createStream() method returns an OutputStream object. Use the OutputStream object to load the object into the cache.
If the attributes have not already been defined for the object, then set them using the createStream() method. The system manages local and distributed disk objects differently; the determination of local or distributed is made when the system creates the object, based on the attributes.
Example 9-19 shows a loader object that loads a StreamAccess object into the cache.
import oracle.ias.cache.*; class YourObjectLoader extends CacheLoader { public Object load(Object handle, Object args) { OutputStream = out; Attributes attr = new Attributes(); attr.setFlags(Attributes.DISTRIBUTE); try { out = createStream(handle, attr); out.write((byte[])getInfofromsomewhere()); } catch (Exception ex) { // translate exception to CacheException, and log exception throw exceptionHandler("exception in write", ex) } return out; } }
A pool object is a special cache object that the Java Object Cache manages. A pool object contains a set of identical object instances. The pool object itself is a shared object; the objects within the pool are private objects that the Java Object Cache manages. Users access individual objects within the pool with a check out, using a pool access object, and then return the objects to the pool when they are no longer needed.
This section covers the following topics:
To create a pool object, use CacheAccess.createPool(). The CreatePool() method takes as arguments a PoolInstanceFactory, and an Attributes object, plus two integer arguments. The integer arguments specify the maximum pool size and the minimum pool size. By supplying a group name as an argument to CreatePool(), a pool object is associated with a group.
Attributes, including TimeToLive or IdleTime can be associated with a pool object. These attributes can be applied to the pool object itself, when specified in the attributes set with CacheAccess.createPool(), or they can be applied to the objects within the pool individually.
Using CacheAccess.createPool(), specify minimum and maximum sizes with the integer arguments. Specify the minimum first. It sets the minimum number of objects to create within the pool. The minimum size is interpreted as a request rather than a guaranteed minimum. Objects within a pool object are subject to removal from the cache due to lack of resources, so the pool can decrease the number of objects below the requested minimum value. The maximum pool size puts a hard limit on the number of objects available in the pool.
Example 9-20 shows how to create a pool object.
import oracle.ias.cache.*; try { CacheAccess cacc = CacheAccess.getAccess("Stock-Market"); Attributes attr = new Attributes(); QuoteFactory poolFac = new QuoteFactory(); // set IdleTime for an object in the pool to three minutes attr.setIdleTime(180); // create a pool in the "Stock-Market" region with a minimum of // 5 and a maximum of 10 object instances in the pool cacc.createPool("get Quote", poolFac, attr, 5, 10); cacc.close(); } catch(CacheException ex) { // handle exception } }
To access objects in a pool, use a PoolAccess object. The PoolAccess.getPool() static method returns a handle to a specified pool. The PoolAccess.get() method returns an instance of an object from within the pool (this checks out an object from the pool). When an object is no longer needed, return it to the pool, using the PoolAccess.returnToPool() method, which checks the object back into the pool. Finally, call the PoolAccess.close() method when the pool handle is no longer needed.
Example 9-21 describes the calls that are required to create a PoolAccess object, check an object out of the pool, and then check the object back in and close the PoolAccess object.
PoolAccess pacc = PoolAccess.getPool("Stock-Market", "get Quote"); //get an object from the pool GetQuote gq = (GetQuote)pacc.get(); // do something useful with the gq object // return the object to the pool pacc.returnToPool(gq); pacc.close();
The Java Object Cache instantiates and removes objects within a pool, using an application-defined factory object--a PoolInstanceFactory. The PoolInstanceFactory is an abstract class with two methods that you must implement: createInstance() and destroyInstance().
The Java Object Cache calls createInstance() to create instances of objects that are being accumulated within the pool. The Java Object Cache calls destroyInstance() when an instance of an object is being removed from the pool. (Object instances from within the pool are passed into destroyInstance().)
The size of a pool object, that is the number of objects within the pool, is managed using these PoolInstanceFactory() methods. The system decreases or increases the size and number of objects in the pool, based on demand, and based on the values of the TimeToLive or IdleTime attributes.
Example 9-22 shows the calls required when implementing a PoolInstanceFactory.
import oracle.ias.cache.*; public class MyPoolFactory implements PoolInstanceFactory { public Object createInstance() { MyObject obj = new MyObject(); obj.init(); return obj; } public void destroyInstance(Object obj) { ((MyObject)obj).cleanup(); } }
Object pools are a collection of serially reusable objects. A user "checks out" an object from the pool to perform a function, then "checks in" the object back to the pool when done. During the time the object is checked out, the user has exclusive use of that object instance. After the object is checked in, the user gives up all access to the object. While the object is checked out, the user can apply temporary modifications to the pool object (add state) to allow it to execute the current task. Since some cost is incurred to add these modifications, it would be beneficial to allow the user to, whenever possible, get the same object from the pool with the modifications already in place. Since the 9.0.2 version of the Java Object Cache, the only way to do this was never to check in the object, which would then defeat the purpose of the pool. To support the pool requirement described in this paragraph, the functionality described in the following two paragraphs has been added to the pool management of the Java Object Cache.
Objects checked into the pool using the returnToPool method of the PoolAccess object maintain an association with the last PoolAccess object that referenced the object. When the PoolAccess handle requests an object instance, the same object it had previously is returned. This association will be terminated if the PoolAccess handle is closed, the PoolAccess.release method is called, or the object is given to another user. Before the object is given to another user, a callback is made to determine if the user is willing to give up the association with the object. If the user is not willing to dissolve the association, the new user is not given access to the object. The interface PoolAffinityFactory extends the interface PoolInstanceFactory, adding the callback method affinityRelease. This method should return true if the association can be broken, and false otherwise.
If the entire pool is invalidated, the affinityRelease method is not called. Object instance cleanup should then be done with the PoolInstanceFactory.instanceDestroy method.
When running in local mode, the Java Object Cache does not share objects or communicate with any other caches running locally on the same system or remotely across the network. Object persistence across system shutdowns or program failures is not supported when running in local mode.
By default, the Java Object Cache runs in local mode, and all objects in the cache are treated as local objects. When the Java Object Cache is configured in local mode, the cache ignores the DISTRIBUTE attribute for all objects.
In distributed mode, the Java Object Cache can share objects and communicate with other caches running either locally on the same system or remotely across the network. Object updates and invalidations are propagated between communicating caches. Distributed mode supports object persistence across system shutdowns and program failures.
This section covers the following topics:
To configure the Java Object Cache to run in distributed mode, set the value of the distribute and discoveryAddress configuration properties in the javacache.xml file.
To start the Java Object Cache in distributed mode, set the isDistributed attribute to true in the configuration file. "Java Object Cache Configuration" describes how to do this.
In distributed mode, invalidations, destroys, and replaces are propagated through the messaging system of the cache. The messaging system requires a known host name and port address to allow a cache to join the cache system when it is first initialized. Use the coordinator attribute in the communication section in the javacache.xml file to specify a list of host name and port addresses.
By default, the Java Object Cache sets the coordinator to the value :12345 (this is equivalent to localhost:12345). To eliminate conflicts with other software on the site, have your system administrator set the discoveryAddress.
If the Java Object Cache spans systems, then configure multiple coordinator entries, with one hostname:port pair specified for each node. Doing this avoids any dependency on a particular system being available or on the order the processes are started. Also see "Java Object Cache Configuration".
When the Java Object Cache runs in distributed mode, individual regions, subregions, groups, and objects can be either local or distributed. By default, objects, regions, subregions, and groups are defined as local. To change the default local value, set the DISTRIBUTE attribute when the object, region, or group is defined.
A distributed cache can contain both local and distributed objects.
Several attributes and methods in the Java Object Cache allow you to work with distributed objects and control the level of consistency of object data across the caches. Also see "Cached Object Consistency Levels".
When updating, invalidating, or destroying objects across multiple caches, it might be useful to know when the action has completed at all the participating sites. Setting the REPLY attribute causes all participating caches to send a reply to the originator when a requested action has completed for the object. The CacheAccess.waitForResponse() method allows the user to block until all remote operations have completed.
To wait for a distributed action to complete across multiple caches, use CacheAccess.waitForResponse(). To ignore responses, use the CacheAccess.cancelResponse() method, which frees the cache resources used to collect the responses.
Both CacheAccess.waitForResponse() and CacheAccess.cancelResponse() apply to all objects that are accessed by the CacheAccess object. This allows the application to update a number of objects, then wait for all the replies.
Example 9-23 illustrates how to set an object as distributed and handle replies when the REPLY attribute is set. In this example, you can also set the attributes for the entire region. Additionally, you can also set attributes for a group or individual object, as appropriate for your application.
import oracle.ias.cache.*; CacheAccess cacc; String obj; Attributes attr = new Attributes (); MyLoader loader = new MyLoader(); // mark the object for distribution and have a reply generated // by the remote caches when the change is completed attr.setFlags(Attributes.DISTRIBUTE|Attributes.REPLY); attr.setLoader(loader); CacheAccess.defineRegion("testRegion",attr); cacc = CacheAccess.getAccess("testRegion"); // create region with //distributed attributes obj = (String)cacc.get("testObject"); cacc.replace("testObject", obj + "new version"); // change will be // propagated to other caches cacc.invalidate("invalidObject"); // invalidation is propagated to other caches try { // wait for up to a second,1000 milliseconds, for both the update // and the invalidate to complete cacc.waitForResponse(1000); catch (TimeoutException ex) { // tired of waiting so cancel the response cacc.cancelResponse(); } cacc.close(); }
When updating objects across multiple caches, or when multiple threads access a single object, you can coordinate the update action. Setting the SYNCHRONIZE attribute enables synchronized updates and requires an application to obtain ownership of an object before the object is loaded or updated.
The SYNCHRONIZE attribute also applies to regions, subregions, and groups. When the SYNCHRONIZE attribute is applied to a region, subregion, or group, ownership of the region, subregion, or group must be obtained before an object can be loaded or replaced in the region, subregion, or group.
Setting the SYNCHRONIZE_DEFAULT attribute on a region, subregion, or group applies the SYNCHRONIZE attribute to all of the objects within the region, subregion, or group. Ownership must be obtained for the individual objects within the region, subregion, or group before they can be loaded or replaced.
To obtain ownership of an object, use CacheAccess.getOwnership(). After ownership is obtained, no other CacheAccess instance is allowed to load or replace the object. Reads and invalidation of objects are not affected by synchronization.
After ownership has been obtained and the modification to the object is completed, call CacheAccess.releaseOwnership() to release the object. CacheAccess.releaseOwnership() waits up to the specified time for the updates to complete at the remote caches. If the updates complete within the specified time, ownership is released; otherwise, a TimeoutException is thrown. If the method times out, call CacheAccess.releaseOwnership() again. CacheAccess.releaseOwnership()must return successfully for ownership to be released. If the timeout value is -1, then ownership is released immediately, without waiting for the responses from the other caches.
Example 9-24 illustrates distributed caching using SYNCHRONIZE and SYNCHRONIZE_DEFAULT.
import oracle.ias.cache.*; CacheAccess cacc; String obj; Attributes attr = new Attributes (); MyLoader loader = new MyLoader(); // mark the object for distribution and set synchronize attribute attr.setFlags(Attributes.DISTRIBUTE|Attributes.SYNCHRONIZE); attr.setLoader(loader); //create region CacheAccess.defineRegion("testRegion"); cacc = CacheAccess.getAccess("testRegion"); cacc.defineGroup("syncGroup", attr); //define a distributed synchronized group cacc.defineObject("syncObject", attr); // define a distributed synchronized object attr.setFlagsToDefaults() // reset attribute flags // define a group where SYNCHRONIZE is the default for all objects in the group attr.setFlags(Attributes.DISTRIBUTE|Attributes.SYNCHRONIZE_DEFAULT); cacc.defineGroup("syncGroup2", attr); try { // try to get the ownership for the group don't wait more than 5 seconds cacc.getOwnership("syncGroup", 5000); obj = (String)cacc.get("testObject", "syncGroup"); // get latest object // replace the object with a new version cacc.replace("testObject", "syncGroup", obj + "new version"); obj = (String)cacc.get("testObject2", "syncGroup"); // get a second object // replace the object with a new version cacc.replace("testObject2", "syncGroup", obj + "new version"); } catch (TimeoutException ex) { System.out.println("unable to acquire ownership for group"); cacc.close(); return; } try { cacc.releaseOwnership("syncGroup",5000); } catch (TimeoutException ex) { // tired of waiting so just release ownership cacc.releaseOwnership("syncGroup", -1)); } try { cacc.getOwnership("syncObject", 5000); // try to get the ownership for the object // don't wait more than 5 seconds obj = (String)cacc.get("syncObject"); // get latest object cacc.replace("syncObject", obj + "new version"); // replace the object with a new version } catch (TimeoutException ex) { System.out.println("unable to acquire ownership for object"); cacc.close(); return; } try { cacc.releaseOwnership("syncObject", 5000); } catch (TimeoutException ex) { cacc.releaseOwnership("syncObject", -1)); // tired of waiting so just release ownership } try { cacc.getOwnership("Object2", "syncGroup2", 5000); // try to get the ownership for the object // where the ownership is defined as the default for the group don't wait more than 5 seconds obj = (String)cacc.get("Object2", "syncGroup2"); // get latest object // replace the object with new version cacc.replace("Object2", "syncGroup2", obj + "new version"); } catch (TimeoutException ex) { System.out.println("unable to acquire ownership for object"); cacc.close(); return; } try { cacc.releaseOwnership("Object2", 5000); } catch (TimeoutException ex) { cacc.releaseOwnership("Object2", -1)); // tired of waiting so just release ownership } cacc.close(); }
Within the Java Object Cache, each cache manages its own objects locally within its JVM process. In distributed mode, when using multiple processes or when the system is running on multiple sites, a copy of an object can exist in more than one cache.
The Java Object Cache allows you to specify the consistency level that is required between copies of objects that are available in multiple caches. The consistency level that you specify depends on the application and the objects being cached. The supported levels of consistency vary, from none to all copies of objects being consistent across all communicating caches.
Setting object attributes specifies the level of consistency. The consistency between objects in different caches is categorized into the following four levels:
If there are no consistency requirements between objects in distributed caches, then define an object as a local object. (When Attributes.DISTRIBUTE is unset, this specifies a local object.) Local is the default setting for objects. For local objects, all updates and invalidation are visible to only the local cache.
To distribute object updates across distributed caches, define an object as distributed by setting the DISTRIBUTE attribute. All modifications to distributed objects are broadcast to other caches in the system. Using this level of consistency does not control or specify when an object is loaded into the cache or updated, and does not provide notification as to when the modification has completed in all caches.
To distribute object updates across distributed caches and wait for the change to complete before continuing, set the object's DISTRIBUTE and REPLY attributes. When you set these attributes, notification occurs when a modification has completed in all caches. When you set Attributes.REPLY for an object, replies are sent back to the modifying cache when the modification has been completed at the remote site. These replies are returned asynchronously--that is, the CacheAccess.replace() and CacheAccess.invalidate() methods do not block. Use the CacheAccess.waitForResponse() method to wait for replies and block.
To use the highest level of consistency of the Java Object Cache, set the appropriate attributes on the region, subregion, group, or object to make objects act as synchronized objects.
When you set Attributes.SYNCHRONIZE_DEFAULT on a region, subregion, or group, it sets the SYNCHRONIZE attribute for all the objects within the region, subregion, or group.
When you set Attributes.SYNCHRONIZE on an object, it forces applications to obtain ownership of the object before the object can be loaded or modified. Setting this attribute effectively serializes write access to objects. To obtain ownership of an object, use the CacheAccess.getOwnership() method. When you set the Attributes.SYNCHRONIZE attribute, notification is sent to the owner when the update is completed. Use CacheAccess.releaseOwnership() to block until any outstanding updates have completed and the replies are received. This releases ownership of the object so that other caches can update or load the object.
When using this level of consistency, with Attributes.SYNCHRONIZE, the CacheLoader.load() method should call CacheLoader.netSearch() before loading the object from an external source. Calling CacheLoader.netSearch() in the load method tells the Java Object Cache to search all other caches for a copy of the object. This prevents different versions of the object from being loaded into the cache from an external source. Proper use of the SYNCHRONIZE attribute, along with the REPLY attribute and the invalidate method, should guarantee consistency of objects across the cache system
To take advantage of the distributed functionality of the Java Object Cache or to share a cached object among servlets, some minor modification to an applications deployment may be necessary. Any user-defined objects that will be shared among servlets or distributed among JVMs must be loaded by the system class loader. By default, objects that are loaded by a servlet are loaded by the context class loader. These objects are visible to only the servlets within the context that loaded them. The object definition is not available to other servlets or to the cache in another JVM. If the object is loaded by the system class loader, the object definition is available to other servlets and to the cache on other JVMs.
With the Apache JServ servlet environment (JServ), the preceding functionality was accomplished by including the cached object in the classpath definition available when the JServ process was started.
With OC4J, the system classpath is derived from the manifest of the oc4j.jar file and any associated JAR files, including cache.jar. The classpath in the environment is ignored. To include a cached object in the classpath for OC4J, copy the class file to ORACLE_HOME/
javacache/sharedobjects/classes or add it to the JAR file ORACLE_HOME
/javacache/cachedobjects/share.jar. Both the classes directory and the share.jar file have been included in the manifest for cache.jar.
<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://www.oracle.com/oracle/ias/cache/configuration" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.oracle.com/oracle/ias/cache/configuration" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="cache-configuration" type="CacheConfigurationType"> <xs:annotation> <xs:documentation>Oracle JavaCache implementation</xs:documentation> </xs:annotation> </xs:element> <xs:complexType name="CacheConfigurationType"> <xs:sequence> <xs:element name="logging" type="loggingType" minOccurs="0"/> <xs:element name="communication" type="communicationType" minOccurs="0"/> <xs:element name="persistence" type="persistenceType" minOccurs="0"/> <xs:element name="region-name-separator" type="xs:string" minOccurs="0"/> <xs:element name="preload-file" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="max-objects" type="xs:positiveInteger" default="1000" minOccurs="0"/> <xs:element name="max-size" type="xs:positiveInteger" default="1000" minOccurs="0"/> <xs:element name="clean-interval" type="xs:positiveInteger" default="60" minOccurs="0"/> <xs:element name="ping-interval" type="xs:positiveInteger" default="60" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="loggingType"> <xs:sequence> <xs:element name="location" type="xs:string" minOccurs="0"/> <xs:element name="level" type="loglevelType" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="communicationType"> <xs:sequence> <xs:element name="isDistributed" type="xs:boolean" default="false" minOccurs="0"/> <xs:element name="coordinator" type="coordinatorType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="coordinatorType"> <xs:attribute name="ip" type="xs:string"/> <xs:attribute name="discovery-port" type="xs:positiveInteger" use="required"/> </xs:complexType> <xs:complexType name="persistenceType"> <xs:sequence> <xs:element name="location" type="xs:string"/> <xs:element name="disksize" type="xs:positiveInteger" default="30" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:simpleType name="loglevelType"> <xs:restriction base="xs:token"> <xs:enumeration value="OFF"/> <xs:enumeration value="FATAL"/> <xs:enumeration value="ERROR"/> <xs:enumeration value="DEFAULT"/> <xs:enumeration value="WARNING"/> <xs:enumeration value="TRACE"/> <xs:enumeration value="INFO"/> <xs:enumeration value="DEBUG"/> </xs:restriction> </xs:simpleType> </xs:schema>
<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://www.oracle.com/oracle/ias/cache/configuration/declarativ e" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.oracle.com/oracle/ias/cache/configuration/declarative" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:complexType name="CacheType"> <xs:sequence maxOccurs="unbounded"> <xs:element name="region" type="regionType"/> </xs:sequence> </xs:complexType> <xs:complexType name="regionType"> <xs:sequence> <xs:element name="attributes" type="attributesType" minOccurs="0"/> <xs:element name="region" type="regionType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="group" type="groupType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="cached-object" type="cached-objectType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> </xs:complexType> <xs:complexType name="attributesType"> <xs:sequence> <xs:element name="time-to-live" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="default-ttl" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="idle-time" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="version" type="xs:string" minOccurs="0"/> <xs:element name="max-count" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="priority" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="size" type="xs:positiveInteger" minOccurs="0"/> <xs:element name="flag" minOccurs="0" maxOccurs="unbounded"> <xs:simpleType> <xs:restriction base="flagType"> <xs:enumeration value="distribute"/> <xs:enumeration value="reply"/> <xs:enumeration value="synchronize"/> <xs:enumeration value="spool"/> <xs:enumeration value="group_ttl_destroy"/> <xs:enumeration value="original"/> <xs:enumeration value="synchronize-default"/> <xs:enumeration value="allownull"/> <xs:enumeration value="measure"/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="event-listener" type="event-listenerType" minOccurs="0"/> <xs:element name="cache-loader" type="userDefinedObjectType" minOccurs="0"/> <xs:element name="capacity-policy" type="userDefinedObjectType" minOccurs="0"/> <xs:element name="user-defined" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="key" type="xs:string"/> <xs:element name="value" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:simpleType name="flagType"> <xs:list itemType="xs:token"/> </xs:simpleType> <xs:complexType name="userDefinedObjectType"> <xs:sequence> <xs:element name="classname" type="xs:string"/> <xs:element name="parameter" type="propertyType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="propertyType"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="event-listenerType"> <xs:sequence> <xs:element name="classname" type="xs:string"/> </xs:sequence> <xs:attribute name="handle-event" type="handle-eventType" use="required"/> <xs:attribute name="default" type="xs:boolean"/> </xs:complexType> <xs:simpleType name="handle-eventType"> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:token"/> </xs:simpleType> <xs:enumeration value="object-invalidated"/> <xs:enumeration value="object-updated"/> </xs:restriction> </xs:simpleType> <xs:complexType name="groupType"> <xs:sequence> <xs:element name="attributes" type="attributesType" minOccurs="0"/> <xs:element name="group" type="groupType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="cached-object" type="cached-objectType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> </xs:complexType> <xs:complexType name="cached-objectType"> <xs:sequence> <xs:element name="attributes" type="attributesType" minOccurs="0"/> <xs:element name="name" type="nameType" minOccurs="0"/> <xs:element name="object" type="userDefinedObjectType" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="nameType"> <xs:choice> <xs:element name="string-name" type="xs:string"/> <xs:element name="object-name" type="userDefinedObjectType"/> </xs:choice> </xs:complexType> </xs:schema>
|
Copyright © 1996, 2003 Oracle Corporation. All Rights Reserved. |
|