Skip Headers

Oracle Application Server TopLink Application Developer's Guide
10g (9.0.4)

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

Go to previous page Go to next page

8
Cache

A cache is a repository that stores recently used objects for an application. Holding objects in the cache helps you minimize database access, and improves application performance.

Oracle Application Server TopLink uses two object caches: the session cache maintains objects retrieved from and written to the database; and the Unit of Work cache holds objects while they participate in transactions. These caches maintain objects based on class and primary key values.

This chapter explores cache use, and discusses the following topics:

Introduction to Cache Concepts

The cache is a key OracleAS TopLink component. You use the cache to improve application performance and manage user access to the database. This section introduces concepts that help you optimize the way your application uses its caches.

Cache Architecture

The session cache and the Unit of Work cache work together with the database connection to manage objects in an OracleAS TopLink application. The object life cycle relies on these three mechanisms.

Figure 8-1 Object Life Cycle and the OracleAS TopLink Caches

Text description of cacharch.gif follows.

Text description of the illustration cacharch.gif

Session Cache

The session cache is a shared cache that services clients attached to a given database session. When you read data from or write data to the database, OracleAS TopLink saves a copy in the session cache and provides that data to all other processes in the session.

OracleAS TopLink adds objects to the cache from:

You can configure queries to search the cache for existing data.If the data exist in the cache, rather than perform a database read, OracleAS TopLink returns the cached data.

For more information about query cache usage, see "In-Memory Query Cache Usage".

Unit of Work Cache

The Unit of Work cache services operations within the Unit of Work. It maintains and isolates objects, and writes changed or new objects to the session cache after the Unit of Work commits changes to the database.

Stale Data

Stale data is an artifact of caching in which an object is not the most recent version. To avoid stale data, implement an appropriate cache locking strategy.

Cache Locking

Cache locking regulates when processes read or write an object. Depending on how you configure it, cache locking determines whether a process can read or write an object that is in use with another process. Cache locking also enables you to manage stale data issues.

Distributed Cache Synchronization

When you deploy your OracleAS TopLink application in a cluster, the cluster generally includes several caches. Because each cache services a different application, this raises the possibility that changes from one application may not appear in the other applications in the cluster.

Distributed cache synchronization reduces the occurrence of stale data across the caches in the system. When an object changes in one cache, distributed cache synchronization enables you to update the other caches in the cluster to replace stale data.

For more information about distributed cache synchronization, see "Distributed Cache Synchronization".

Cluster

An OracleAS TopLink cluster is a collection of servers that:

Discovery

Discovery occurs when servers in a cluster learn of other servers in the cluster. Discovery uses a multicast protocol to monitor sessions as they join and leave the OracleAS TopLink cluster.

Message Transport

A message transport is the messaging protocol servers in a cluster use to send and receive messages. OracleAS TopLink uses a transport protocol to exchange object updates between cooperating sessions.

Name Service

A name service enables you to search for objects on remote caches. OracleAS TopLink cache synchronization uses a name service when it looks up connections to other sessions in the OracleAS TopLink cluster.

If you use RMI as a transport, the RMI Registry provides lookup capabilities. In most other cases, the Java Naming and Directory Interface (JNDI) provides lookup functionality.

Propagation Modes

The propagation mode determines when a client regains control after it propagates object changes. OracleAS TopLink supports synchronous and asynchronous propagation modes.

Synchronous Update Mode

When you propagate updates synchronously, OracleAS TopLink prevents the committing client from performing other tasks until the remote merge process is complete.

Asynchronous Update Mode

In asynchronous mode, OracleAS TopLink creates separate threads to propagate changes to remote servers. OracleAS TopLink returns control to the client immediately after the local commit, whether or not the changes merge successfully on the remote servers. This offers superior performance for applications that are somewhat tolerant of stale data.

Cache Locking and Isolation

By default, OracleAS TopLink optimizes concurrency to minimize cache locking during reads or writes. Use the default OracleAS TopLink isolation level unless you have a very specific reason to change it.

Use the following application programming interface (API) on Databaselogin to change the OracleAS TopLink isolation level:

login.setCacheTransactionIsolation(int cacheTransactionIsolation)

The available settings for cacheTransactionIsolation are:

Configuring the Cache

A well-managed cache makes your application more efficient. There are very few cases in which you turn the cache off entirely, as the cache reduces database access, and is an important part of managing object identity.

To make the most of your cache strategy and to minimize your application's exposure to stale data, we recommend the following:

Configure the cache on a per-class basis

If other applications can modify the data used by a particular class, use a weaker style of cache for the class. For example, the SoftCacheWeakIdentityMap or WeakIdentityMap minimizes the length of time the cache maintains a de-referenced object.

For more information about configuring cache usage on a per-class basis, see "Working with Identity Maps" in the Oracle Application Server TopLink Mapping Workbench User's Guide.


Note:

If your application reaches a low system memory condition frequently enough or if your platform's JVM treats weak and soft references the same, the objects in the sub-cache may be garbage collected so often that you will not benefit from the performance improvement provided by the sub-cache. If this is the case, Oracle recommends that you use the HardCacheWeakIdentityMap. It is identical to the SoftCacheWeakIdentityMap except that it uses hard references in the sub-cache. This guarantees that your application will benefit from the performance improvement provided by the sub-cache.


Force a cache refresh when required on a per-query basis

Any query can include a flag that forces a cache refresh to the database.

For more information about configuring cache refresh on a per-query basis, see "Refresh".

Distributed Cache Synchronization

The need to maintain up-to-date data for all applications is a key design challenge for building a distributed application environment. The difficulty of this increases as the number of servers within an environment increases. OracleAS TopLink provides a distributed cache synchronization feature that ensures data in applications remains current.

Cache synchronization in no way eliminates the need for an effective locking policy. However, it does reduce the number of optimistic lock exceptions encountered in a distributed architecture, and decreases the number of failed or repeated transactions in an application.

OracleAS TopLink provides cache synchronization at the session level. This ensures that object updates associated with a given session propagate to the caches on all other servers in the cluster.

This section describes:

Configuring Cache Synchronization in the sessions.xml File

Because each application server approaches caching differently, you must configure cache synchronization to work effectively within the distributed system.

For more information about choosing cache configuration options, see the application server or J2EE container documentation.

To enable and configure cache synchronization in the sessions.xml file, specify the cache-synchronization-manager element, and configure the required sub-elements.

Example 8-1 illustrates how to configure cache synchronization in the sessions.xml file for a session that:

Example 8-1 Configuring Cache Synchronization in the sessions.xml File

<cache-synchronization-manager>
    <clustering-service>
        oracle.toplink.remote.rmi.RMIJNDIClusteringService
    </clustering-service>
    <jndi-user-name>userName</jndi-user-name>
    <jndi-password>password</jndi-password>
    <naming-service-initial-context-factory-name>
        oracle.com.evermind.server.rmi.RMIInitialContextFactory
    </naming-service-initial-context-factory-name>
    <naming-service-url>ormi://hostname:23791/appName</naming-service-url>
</cache-synchronization-manager>

The configuration in Example 8-1 includes the name, password, context factory class, and URL. Oracle Application Server Containers for J2EE requires all four sub-elements to enable name lookup on remote hosts. Other servers require different values for the context factory and URL.

For Oracle Application Server Containers for J2EE, the URL element includes the ormi:// protocol, the local host name and RMI server port, and the name of the application in which the OracleAS TopLink session is deployed.

Clustering Service

The clustering-service element specifies the name service and transport combination used to communicate changes. Choose the combination that works best with your application. Your choices are:

Example 8-2 Configuring a Clustering Service in the sessions.xml File

<cache-synchronization-manager>
    <clustering-service>
        oracle.toplink.remote.rmi.RMIJNDIClusteringService
    </clustering-service>
    ...
</cache-synchronization-manager>

Discovery

Discovery occurs when servers in a cluster learn of other servers in the cluster and uses a multicast protocol to monitor sessions as they join and leave the OracleAS TopLink cluster. If you are running OracleAS TopLink with other Oracle Application Server 10g components, ensure the port you select does not conflict with other components. If OracleAS TopLink's default discovery configuration conflicts with settings for other services on the same host, you can override the discovery settings.

You can configure discovery to use specific optional multicast socket options, including:

Example 8-3 Configuring Discovery in the sessions.xml File

<cache-synchronization-manager>
    <clustering-service> ... </clustering-service>
    <multicast-port>6020</multicast-port>
    <multicast-group-address>228.1.2.3</multicast-group-address>
    <packet-time-to-live>3</packet-time-to-live>
    ...
</cache-synchronization-manager>


Note:

When you select JMS as the transport mechanism in the clustering-service element, OracleAS TopLink ignores the discovery setting.


Name Service

A name service enables you to search for objects on remote caches. JNDI provides the name service for most applications, and offers the following optional elements to customize JNDI support in your application:

Not all servers require all four optional elements.

Example 8-4 Configuring JNDI Name Service in the sessions.xml File for WLS

<cache-synchronization-manager>
    <clustering-service> ... </clustering-service>
    <naming-service-initial-context-factory-name>
        weblogic.jndi.WLInitialContextFactory
    </naming-service-initial-context-factory-name>
    <naming-service-url>t3://hostName:7001</naming-service-url>
</cache-synchronization-manager>

Using the Java Message Service

The JMS API is a protocol for communication that provides asynchronous communication between components in a distributed computing environment. Because OracleAS TopLink integrates with the JMS publish/subscribe mechanism, use JMS to improve the scalability of your cache synchronization.

For more information about the JMS API, see the JMS specification at

http://java.sun.com/products/jms
Preparing to use JMS

You must configure a JMS service in the environment before OracleAS TopLink can leverage the service. To enable the service:

  1. Configure a JMS connection factory and note the name. OracleAS TopLink uses the factory name to look-up the factory.

  2. Configure a JMS topic and note the name. OracleAS TopLink uses the topic name to look-up the topic.

  3. Configure the OracleAS TopLink sessions.xml file to use the factory and topic names.

  4. Start the JMS service.

For more information on how to complete steps 1, 2, and 4, see the JMS service provider documentation.

For more information on how to complete step 3, see "Configuring JMS in sessions.xml".

Example 8-5 illustrates a jms.xml configuration file for Oracle Application Server Containers for J2EE. Note that the host and port of the topic connection factory is the host and port of the JMS server hosting the topic, and not the host or port of the local JMS server.

Example 8-5 Example of the Oracle Application Server Containers for J2EE jms.xml File

<jms-server port="9128">
    <topic name="MyCacheSyncTopic" location="jms/MyCacheSyncTopic"/>
    <topic-connection-factory 
      host="micky" 
      port="9127" 
      name="Cache Sync Topic Factory" 
      location="jms/MyTopicFactory" 
      password="password" 
      username="admin"/> 
    <log>
        <file path="../log/jms.log"/> 
    </log>
</jms-server>

Configuring JMS in sessions.xml

To configure JMS in the sessions.xml file, use the following optional elements:

Example 8-6 JMS Entries in the sessions.xml File

<cache-synchronization-manager>
    <clustering-service>
        oracle.toplink.remote.jms.JMSClusteringService 
    </clustering-service>
    <jms-topic-connection-factory-name>
        jms/MyTopicFactory 
    </jms-topic-connection-factory-name>
    <jms-topic-name>jms/MyCacheSyncTopic</jms-topic-name>
    ...
</cache-synchronization-manager>

Note that JMS neither requires nor makes use of discovery.

Configuring JMS for Oracle Application Server Containers for J2EE

When you use JMS in Oracle Application Server Containers for J2EE, set the naming service URL to the hostname of the JMS server hosting the topic. Example 8-7 illustrates this for an OracleAS TopLink session running in Oracle Application Server Containers for J2EE using JMS.

Example 8-7 Configuring OracleAS TopLink with JMS for Oracle Application Server Containers for J2EE

<cache-synchronization-manager>
    <clustering-service>
        oracle.toplink.remote.jms.JMSClusteringService 
    </clustering-service>
    <jndi-user-name>admin</jndi-user-name>
    <jndi-password>password</jndi-password>
    <jms-topic-connection-factory-name>
        jms/MyTopicFactory 
    </jms-topic-connection-factory-name>
    <jms-topic-name>jms/MyCacheSyncTopic</jms-topic-name>
    <naming-service-initial-context-factory-name>
        oracle.com.evermind.server.rmi.RMIInitialContextFactory 
    </naming-service-initial-context-factory-name>
    <naming-service-url>ormi://micky</naming-service-url>
</cache-synchronization-manager>

Synchronous and Asynchronous Propagation

The Cache Synchronization Manager enables you to specify the propagation mode for your OracleAS TopLink application:

The optional is-asynchronous element controls the propagation mode, regardless of the transport used. By default, propagation occurs asynchronously.

Example 8-8 Configuring Propagation Mode

<cache-synchronization-manager>
    <clustering-service>...</clustering-service>
    <is-asynchronous>false</is-asynchronous>
    ...
</cache-synchronization-manager>

Error Handling

You can define error handlers to respond to raised exceptions. The should-remove-connection-on-error element (an optional sub-element of cache-synchronization-manager) specifies whether a connection to another session is discarded if an error occurs while sending an update. By default, OracleAS TopLink discards connections when errors occur.

Example 8-9 Configuring Error Handling

<cache-synchronization-manager>
    <clustering-service>...</clustering-service>
    <should-remove-connection-on-error>false</should-remove-connection-on-error>
    ...
</cache-synchronization-manager>

Explicit Query Refreshes

Some distributed systems require only a small number of objects to be consistent across the servers in the system. Conversely, other systems require that several specific objects must always be guaranteed to be up-to-date, regardless of the cost. If you build such a system, you can explicitly refresh selected objects from the database at appropriate intervals without incurring the full cost of distributed cache synchronization.

To implement this type of strategy:

  1. Configure a set of queries that refresh the required objects.

  2. Establish an appropriate refresh policy.

  3. Invoke the queries as required to refresh the objects.

Refresh Policy

When you execute a query, if the required objects are in the cache, OracleAS TopLink returns the cached objects without checking the database for a more recent version. This reduces the number of objects that OracleAS TopLink must build from database results, and is optimal for non-clustered environments. However, this may not always be the best strategy for a clustered environment.

To override this behavior, set a refresh policy that specifies that the objects from the database always take precedence over objects in the cache. This updates the cached objects with the data from the database.

You can implement this type of refresh policy on each OracleAS TopLink descriptor, or just on certain queries, depending upon the nature of the application.

For more information about setting the refresh policy for a descriptor, see "Setting Descriptor Information," in the Oracle Application Server TopLink Mapping Workbench User's Guide.

For more information about setting the refresh policy for a query, see "Refresh".


Note:

Refreshing does not prevent phantom reads from occurring. See "Refreshing Finder Results".


EJB Finders and Refresh Policy

When you invoke a findByPrimaryKey finder, if the object exists in the cache, OracleAS TopLink returns that copy. This is the default behavior, regardless of the refresh policy. To force a database query, you can configure the query to refresh by setting refreshIdentityMapResult() on it.

For more information about caching options, see "Caching Options".

Remote Command Manager

The Remote Command Manager (RCM) enables OracleAS TopLink to send synchronization messages across the network to non-OracleAS TopLink applications. This feature is separate from the standard cache synchronization feature.

When you build a distributed system that includes both OracleAS TopLink and non-OracleAS TopLink applications, use the RCM in place of regular cache synchronization. Do not use RCM and regular OracleAS TopLink cache synchronization concurrently.

This section discusses the RCM, and offers information on:

RCM Implementation Requirements

To enable RCM in a distributed system, enable RCM for all OracleAS TopLink sessions in the system. In addition, non-OracleAS TopLink applications must meet the following criteria to participate in cache synchronization through the RCM:

RCM Structure

The RCM is both modular and pluggable. Figure 8-2 illustrates the components of the RCM.

Figure 8-2 Remote Command Manager Components

Text description of rcm.gif follows.

Text description of the illustration rcm.gif

RCM components include:

CommandManager

The CommandManager is the central point of control for the system.

DiscoveryManager

The DiscoveryManager dynamically maintains the membership of the OracleAS TopLink cluster.

TransportManager

The TransportManager manages the transport level of the message exchange.

CommandProcessor

The CommandProcessor interface sits between the RCM and the application. It is the main integration point for non-OracleAS TopLink applications.

CommandConverter

An implementation of the CommandConverter translates commands between OracleAS TopLink and non-OracleAS TopLink applications. Regular OracleAS TopLink sessions do not require a CommandConverter implementation, because they do not require conversion.

Transmitting Commands From OracleAS TopLink with RCM

The process of initiating and transmitting commands from an OracleAS TopLink application is as follows:

  1. Invoke the getCommandManager() accessor on the session to obtain a CommandManager interface.

  2. Invoke the CommandManager.propagateCommand(command) method to initiate commands from the OracleAS TopLink session. Pass the command to be remotely executed as the command argument.

  3. The TransportManager transmits the command to other members of the cluster.

  4. If the receiving application is:

    • An OracleAS TopLink application, the OracleAS TopLink session executes the command.

    • A non-OracleAS TopLink application (or an application that does not use an OracleAS TopLink session), the application must provide implementation classes for the CommandProcessor and CommandConverter interfaces.

Using Commands on a Non-OracleAS TopLink Application

To send remote commands to the cluster, non-OracleAS TopLink applications invoke the CommandManager.propagateCommand(command) method. The application must provide a CommandConverter interface to convert the application-specific command format to an OracleAS TopLink Command object.

Likewise, when a non-OracleAS TopLink application receives an OracleAS TopLink command, it must implement a converter to translate the command for the CommandManager. To execute the command, a non-OracleAS TopLink application invokes the processCommand(command) method.

RCM Channels

The RCM passes remote commands along virtual channels. The RCM assigns each subscribing service a channel on which to send and receive commands, and all services assigned to a particular channel send (or publish) commands to that channel. Services also act as subscribers to their assigned channel, receiving all the commands published to that channel by other services.

You can assign any number of channels in the system without performance penalty, but any given service may only publish and subscribe to a single channel. You cannot reassign channels dynamically, or while discovery is active.

If you do not set a channel name, RCM assigns a default channel when you add services to the cluster. For example, if you do not set a channel name for any service instance you add to the system, all services subscribe to the same, default channel.

Configuring the RCM

Use the RCM API to configure the RCM. For OracleAS TopLink applications, create the cluster as part of the session initialization (for example: use a session PreLogin event when the session is initialized from the sessions.xml file). Note that neither the OracleAS TopLink Sessions Editor nor the sessions.xml file directly support RCM configuration.

The logical OracleAS TopLink cluster includes any number of OracleAS TopLink session-based applications, and non-OracleAS TopLink applications. Bind non-OracleAS TopLink applications in with OracleAS TopLink code to enable them to access the OracleAS TopLink commands.

Configuring the RCM for OracleAS TopLink Applications

To configure applications that use OracleAS TopLink sessions for RCM:

  1. Create a Remote Command Manager implementation instance for the CommandManager interface. Pass the session as the CommandProcessor argument.

    For example:

    CommandManager rcm = new RemoteCommandManager(session);
    
    
  2. To enable change set propagation between sessions, set the propagating option to true:

    session.setShouldPropagateChanges(true);
    
    
  3. Set the URL that other RCM servers use to look up JNDI names in this Java virtual machine (JVM). For example, for Oracle Application Server Containers for J2EE, the URL can appear as follows:

    rcm.setUrl("ormi://myHostname:23791/myDeployedApplication");
    
    

    For a WebLogic Server, the URL can appear as follows:

    rcm.setUrl("t3://myHostname:7001");
    
    
  4. If you use Oracle Application Server Containers for J2EE, set a valid user and password. This enables the RCM services to look up remote names in JNDI. The user and password combination must be valid on all servers that participate in RCM.

    For example:

    rcm.getTransportManager().setUserName("admin");
    rcm.getTransportManager().setPassword("password");
    
    
  5. If you are using WebLogic Server, leave the remote context properties empty.

    For example:

    rcm.getTransportManager().setRemoteContextProperties(
       new java.util.Hashtable());
  6. (Optional) Set the DiscoveryManager parameters to custom multicast socket settings for your environment.

    For example:

    rcm.getDiscoveryManager().setMulticastGroupAddress("226.1.2.3");
    rcm.getDiscoveryManager().setMulticastPort(3122);
    
    
  7. (Optional) Set the logical channel to assign a channel for the service.

    For example:

    rcm.setChannel("MyChannel");
    
    
  8. (Optional) Set other RCM properties to customize the application.

    For example:

    rcm.setShouldPropagateAsynchronously(false);
    rcm.setShouldRemoveConnectionOnError(true);
    
    

Example 8-10 Enabling RCM on Oracle Application Server Containers for J2EE

CommandManager rcm = new RemoteCommandManager(session);
rcm.setUrl("ormi://ferengi:23791/orderEntryApp");
rcm.getTransportManager().setUserName("admin");
rcm.getTransportManager().setPassword("password");
session.setShouldPropagateChanges(true);

Example 8-11 Enabling RCM on the BEA WebLogic Server

CommandManager rcm = new RemoteCommandManager(session);
rcm.setUrl("t3://ferengi:7001");
rcm.getTransportManager().setRemoteContextProperties(
   new java.util.Hashtable());
session.setShouldPropagateChanges(true);

Configuring RCM for Non-OracleAS TopLink Applications

To configure RCM on applications that do not use the OracleAS TopLink sessions:

  1. Create an application class to implement the CommandProcessor interface.

    For example:

    CommandProcessor processor = new ApplicationCommandProcessor();
    
    
  2. Create a Remote Command Manager implementation instance for the CommandManager interface. Pass the session as the CommandProcessor argument:

    CommandManager rcm = new RemoteCommandManager(processor);
    
    
  3. Create an application class to implement the CommandConverter interface and set an instance of the implementation class on the CommandManager.

    For example:

    CommandConverter converter = new ApplicationCommandConverter();
    rcm.setCommandConverter(converter);
    
    
  4. If you are using WebLogic Server, leave the remote context properties empty.

    For example:

    rcm.getTransportManager().setRemoteContextProperties(
       new java.util.Hashtable());
  5. (Optional) Set the DiscoveryManager parameters to custom multicast socket settings for your environment.

    For example:

    rcm.getDiscoveryManager().setMulticastGroupAddress("226.1.2.3");
    rcm.getDiscoveryManager().setMulticastPort(3122);
    
    
  6. (Optional) Set the logical channel to assign a channel for the service.

    For example:

    rcm.setChannel("MyChannel");
    
    
  7. (Optional) Set other RCM properties to customize the application.

    For example:

    rcm.setShouldPropagateAsynchronously(false);
    rcm.setShouldRemoveConnectionOnError(true);
    
    
  8. Start the RCM service:

    rcm.initialize();
    
    

Example 8-12 Enabling RCM for a Non-OracleAS TopLink Application Using JNDI on Oracle Application Server Containers for J2EE

CommandManager rcm = new RemoteCommandManager(
   new ApplicationCommandProcessor());
rcm.setCommandConverter(
   new ApplicationCommandConverter());
rcm.setUrl("ormi://ferengi:23791/orderEntryApp");
rcm.getTransportManager().setUserName("admin");
rcm.getTransportManager().setPassword("password");
rcm.initialize();

Example 8-13 Enabling RCM for a Non-OracleAS TopLink Application Using JNDI on WebLogic Server

CommandManager rcm = new RemoteCommandManager(
   new ApplicationCommandProcessor());
rcm.setCommandConverter(
   new ApplicationCommandConverter());
rcm.setUrl("t3://ferengi:7001");
rcm.getTransportManager().setRemoteContextProperties(
   new java.util.Hashtable());
rcm.initialize();

Error Handling

Propagated commands often execute on multiple subscribing services. The subscribing services only return results to the publishing server if the command fails. The propagation mode affects error handling when a subscribing node reports a failure:

You can choose to catch and handle exceptions explicitly. The CommandProcessor interface includes the handleException() method for this purpose. Implement this method to catch exceptions thrown from a remote command service. For OracleAS TopLink applications, you can specify an exception handler on the session to handle the exception.

Raised exceptions are either:

Guidelines for Using RCM

When you use RCM, consider the following:

Custom Remote Commands

To create additional custom commands, extend the oracle.toplink.remotecommand.Command class, and implement the executeWithSession(Session) method. If the CommandProcessor interface is an OracleAS TopLink session, this method executes when the service executes.

You can pass instances of these commands to the propagateCommand() method, and publish them for execution on the remote services.


Go to previous page Go to next page
Oracle
Copyright © 2000, 2003 Oracle Corporation.

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