Oracle9i Application Server Oracle9iAS Object Caching Service for Java Developer's Guide
Release 1 (v1.0.2.2)

Part Number A88852-01
Go To Documentation Library
Library
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

3
Getting Started with Object Caching Service for Java

This chapter provides an introduction to the procedures for setting up and working with the Object Caching Service for Java. Very little setup is required before using the Object Caching Service for Java to place Java objects into the cache and retrieve Java objects from the cache. The topics covered in this chapter include:

Importing the Caching Service

The Oracle installer installs the Object Caching Service for Java jar file cache.jar in the directory $ORACLE_HOME/ocs4j/lib on UNIX or in %ORACLE_HOME%\ocs4j\lib on Windows NT.

To use the Object Caching Service for Java, you need to import oracle.ias.cache.

import oracle.ias.cache.*;

Defining a Cache Region

All access to the Object Caching Service for Java is through a CacheAccess object. A CacheAccess object provides access to the cache through 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, defineRegion() initializes the Object Caching Service for Java.

When you define the region, you can also set attributes and create a CacheLoader object. Attributes specify how the Object Caching Service for Java manages objects. The Attributes.setLoader() method sets the name of CacheLoader.

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 Object Caching Service for Java. The second argument defines the attributes for the new region.

See Also:

"Cache Object Attributes" and "Implementing a CacheLoader"  

Defining a Cache Group

When you want to create an association between two or more objects within the cache, create a cache group. Objects are typically associated in a cache group because they need to 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 following code 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();

Defining a Cache Subregion

Define a subregion when you want to create a private name space within a region or within a previously defined subregion. A subregion's name space 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 a subregion's parent.

In the following example, cache subregion is defined 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();

Defining and Using Cache Objects

You may sometimes want to describe to the Object Caching Service for Java how an individual object should be managed within the cache before the object is loaded. Management options can be specified 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, the Object Caching Service for Java uses the default attributes set for the region, subregion, or group with which the object is associated.

Example 3-1 shows how to set attributes for a cache object.

Example 3-1 Setting Cache Attributes

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();
}

Implementing a CacheLoader

Generally, you should use the Object Caching Service for Java to load objects automatically, as needed rather than using the application to directly manage objects in the cache. When an application directly manages objects, it uses the CacheAccess.put() method to insert objects into the cache. To take advantage of automatic loading, you use a CacheLoader object and implement a load() method to insert objects into the cache.

A CacheLoader can be associated with a region, subregion, a group, or an object. Using a CacheLoader allows the Object Caching Service for Java to schedule and manage object loading, and handle the logic for, "if the object is not in cache then load."

When an object is not in the cache, when an application calls CacheAccess.get() or CacheAccess.preLoad(), the CacheLoader executes the load method. When the load method returns, the Object Caching Service for Java 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 CacheAccess.get() 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 that is defined for an individual object is used only to load the object.


Note:

A CacheLoader that is defined for a region, subregion, or group or for more than one cache object needs to be written with concurrent access in mind. The implementation should be thread-safe, since the CacheLoader object is shared. 


Using CacheLoader Methods Within the Load Method

The Object Caching Service for Java supports several CacheLoader methods that you can use within a load() method implementation. Table 3-1 summarizes the available CacheLoader methods.

Table 3-1  CacheLoader Methods for Use in a Load Method
Method  Description 

setAttributes() 

Sets the attributes for the object being loaded. 

netSearch() 

Searches other available caches for the object to load. Objects are uniquely identified by the region name, subregion name, and the object name. 

getName() 

Returns the name of the object being loaded. 

getRegion() 

Returns the name of the region associated with the object being loaded 

createStream() 

Creates a StreamAccess object 

createDiskObject() 

Creates a disk object 

exceptionHandler() 

Converts noncache exceptions into CacheExceptions, with the base set to the original exception 

log() 

Records a messages in the cache service log 

Example 3-2 shows a CacheLoader using the cacheLoader.netSearch() method to check if the object being loaded is available in distributed Object Caching Service for Java caches. If the object is not found using netSearch(), 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 Object Caching Service for Java stores the result as a String.

Example 3-2 Implementing a CacheLoader

import oracle.ias.cache.*;
class YourObjectLoader extends CacheLoader{ 
      public YourObjectLoader () { 
      }
      public Object load(Object handle, Object args) {
         String contents; 
         // check if this object is loaded in another cache 
         try { 
            contents = (String)netSearch(5000); // wait for up to 5 seconds
            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; 
    } 
 } 

Invalidating Cache Objects

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 a 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, destroy the object using the CacheAccess.destroy() method.

An object may be invalidated automatically based on the TimeToLive or IdleTime attributes. When the TimeToLive or IdleTime expires, objects are by default, invalidated and not destroyed (see GROUP_TTL_DESTROY in Table 2-1 for information on changing this default behavior).

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 CacheAccess.invalidate().

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 access 

Destroying Cache Objects

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 may be destroyed automatically based on the TimeToLive or IdleTime attributes. By default, objects are invalidated and are not destroyed. If the objects need to 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.

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

Setting Cache Configuration Properties

During initialization, the Object Caching Service for Java sets values for configuration properties. Table 3-2 lists the configuration properties for Object Caching Service for Java. By default, the first time a region is created, or the default region is accessed, the Object Caching Service for Java initializes the configuration properties. When the Object Caching Service for Java is installed, the installer updates values for certain administrative properties and places the updated values in the OCS4J.properties configuration file, in the directory $ORACLE_HOME/ocs4j/admin on UNIX or in %ORACLE_HOME\ocs4j\admin on Windows NT.

You can modify the OCS4J.properties file to use values other than the default configuration property values. For configuration property values that are not specified in OCS4J.properties, the Object Caching Service for Java uses the default values included in Table 3-2.

When the Object Caching Service for Java is initialized, it uses either the default administration property values, or values specified in OCS4J.properties. No explicit method calls are required to configure the administrative properties using this initialization technique. The Object Caching Service for Java also supports other initialization techniques (see the Cache object methods in the Javadoc for details).

The format for the values in the properties OCS4J.properties file is:

property=value

A # character in a configuration file starts a comment. When the # is in the first column, the entire line is a comment. When the # is occurs after a property value specification, it applies to the remainder of the line.

Table 3-2 lists the valid property names and lists the valid types for each property.

Table 3-2  Object Caching Service for Java Configuration Properties
Configuration Property  Description  Type 

cleanInterval 

Specifies the time, in seconds, between each cache cleaning. At the cache-cleaning interval, the Object Caching Service for Java checks for objects that have been invalidated by the TimeToLive or IdleTime attributes associated with the object.

Default value: 60 

int 

discoveryAddress 

Specifies the address that the Object Caching Service for Java initially contacts to join the caching system, when using distributed caching. The value is in the form, hostname:port. If the hostname is omitted, localhost is used. If the caching service spans systems, a comma separated list of hostnames and ports should be included, with one hostname:port pair specified for each node.

Default Value: :12345 (this is equivalent to localhost:12345). 

String 

diskPath 

Specifies the absolute path to the root for the disk cache (a directory). If this attribute is not set, disk caching is not available.

Default value: null 

String 

distribute 

Indicates whether the cache is distributed. Updates and invalidation for objects that have the distribute property set are propagated to other caches known to the Object Caching Service for Java. If the distribute property is set to false, all objects are treated as local, even when the attributes set on objects are set to distribute.

Default value: false 

boolean 

logFileName 

Specifies the log file name for the default logger implementation.

Default value: $ORACLE_HOME/ocs4j/admin/logs/ocs4j.log on UNIX or %ORACLE_HOME%\ocs4j\admin\logs\ocs4j.log on Windows NT 

String 

logger 

Specifies the class name for the object that implements the CacheLogger interface. The object is instantiated when the Object Caching Service for Java is initialized.

Default value: oracle.ias.cache.DefaultCacheLogger 

String 

logSeverity 

Specifies the logging severity level used for initializing the logger. The valid values are:

  • -1 CacheLogger.OFF

  • 0 CacheLogger.FATAL

  • 3 CacheLogger.ERROR

  • 4 CacheLogger.DEFAULT

  • 6 CacheLogger.WARNING

  • 7 CacheLogger.TRACE

  • 10 CacheLogger.INFO

  • 15 CacheLogger.DEBUG

Default value: CacheLogger.DEFAULT 

int 

maxObjects 

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 

int 

maxSize 

Specifies the maximum size of the memory, in megabytes, available to the Object Caching Service for Java.

Default value: 10 

int 


Note:

Configuration properties are distinct from the Object Caching Service for Java attributes that you specify using the Attributes class. 


Restrictions and Programming Pointers

This section covers restrictions and programming pointers to keep in mind when using the Object Caching Service for Java.

  1. The CacheAccess object should not be shared between threads. This object represents a user to the caching system. The CacheAccess object contains the current state of the user's access to the cache: what object is currently being accessed, what objects are currently owned, and so on. Trying to share the CacheAccess object is unnecessary and can result in nondeterministic behavior.

  2. A CacheAccess object only holds a reference to one cached object at a time. If multiple cached objects are being accessed concurrently, multiple CacheAccess objects should be used. For objects stored in memory, the consequences of not doing this are minor since Java prevents the cached object from being garbage collected even if the cache believes it is not being referenced. For disk objects, if the cache reference is not maintained, the underlying file could be removed by another user or by time-based invalidation, causing unexpected exceptions. To optimize resource management, you should keep the cache reference open as long as the cached object is being used.

  3. A CacheAccess object should always be closed when it is no longer being used. The CacheAccess objects are pooled. They acquire other cache resources on behalf of the user. If the access object is not closed when it is not being used, these resources are not returned to the pool and are not cleaned up until they are garbage collected by the Java VM. If CacheAccess objects are continually allocated and not closed, available resources and a consequent degradation in performance may occur.

  4. When local objects (objects that do not set the Attributes.DISTRIBUTE attribute) are saved to disk using the CacheAccess.save() method they do not survive the termination of the process. By definition, local objects are only visible to the cache instance where they were loaded. If that cache instance goes away for any reason, the objects it manages, including on disk, are lost. If an object needs to survive process termination, both the object and the cache need to be defined DISTRIBUTE.

  5. The cache configuration, also called the cache environment, is local to a cache, this includes the region, subregion, group, and object definitions. The cache configuration is not saved to disk or propagated to other caches. The cache configuration should be defined during the initialization of the application.

  6. If a CacheAccess.waitForResponse() or CacheAccess.releaseOwnership() method call times out, it must be called again until it returns successfully. Call these methods with a -1 timeout value to free up resources, and eliminate waits.

  7. When a group is destroyed or invalidated, distributed definitions take precedence over local definitions. That is, if the group is distributed, all objects in the group will be invalidated or destroyed across the entire cache system even if the individual objects or associated groups are defined as local. If the group is defined as local, local objects within the group are invalidated locally, while distributed objects are invalidated throughout the entire cache system.

  8. When an object or group is defined with the SYNCHRONIZE attribute set, ownership is required to load or replace the object. However, ownership is not required for general access to the object or to invalidate the object.

  9. In general, objects stored in the cache should be loaded by the system class loader defined in the CLASSPATH when the Java VM is initialized, rather than by a user defined class loader. Specifically, any objects that are shared between applications or may be saved or spooled to disk need to be defined in the system CLASSPATH. Failure to do so may result in ClassNotFoundExceptions or ClassCastExceptions.

  10. On some systems, the open file descriptors may be limited by default. On these systems, you may need to change system parameters to improve performance. On UNIX systems, for example, a value of 1024 or greater may be an appropriate value for the number of open file descriptors.

  11. When configured in either local or distributed mode, at startup, one active Object Caching Service for Java cache is created in a Java VM process (that is, in the program running in the Java VM that uses the Object Caching Service for Java API).


Go to previous page Go to next page
Oracle
Copyright © 2001 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Library
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index