Skip Headers
Oracle® Coherence Tutorial for Oracle Coherence
Release 3.6

Part Number E15831-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

3 Accessing the Data Grid from Java

In this exercise, you will develop a simple, Java console-based application to access, update, and remove simple types of information from a Coherence clustered cache. You also get familiar with using the Coherence Java APIs. Using JDeveloper, you will perform the following tasks:

This chapter has the following sections:

3.1 Introduction

All Coherence caches are named, have a lifetime scoped by the cluster instance in which they exist, and implement the com.tangosol.net.NamedCache interface. The NamedCache interface is an extension of java.util.Map and holds data and resources that are shared among the cluster members. Each NamedCache holds data as key/value pairs. Keys and values can be both simple and complex object types. The NamedCache interface provides extensions to the Map interface, such as locking and synchronization, storage integration, queries, event aggregations, and transactions. Table 3-1 describes some of the more commonly used methods within the NamedCache interface.

Table 3-1 Methods in the NamedCache Interface

Method Name Description

void clear()

Removes all entries from the NamedCache.

boolean containsKey(Object key)

Returns true if NamedCache contains an entry for the key.

boolean containsValue(Objectvalue)

Returns true if there is at least one entry with this value in NamedCache.

Object get(Object key)

Gets the entry from NamedCache for that key.

Object put(Object key,Objectvalue)

Puts an object in the cache and returns the previous value (if any).

Object remove(Object key)

Removes the mapping for this key from this map if present. Inherited from ConcurrentMap.

Set entrySet()

Returns a set of key/value pairs.

Collection values()

Gets all values back as a collection.

CacheService getCacheService()

Returns the CacheService that this NamedCache is a part of.


The com.tangosol.net.CacheFactory class is typically used to obtain an instance of a NamedCache. Table 3-2 describes some of the more commonly used methods in the CacheFactory class.

Table 3-2 Methods in the CacheFactory Class

Method Name Description

static Cluster ensureCluster()

Obtains a cluster object running Coherence services.

static void shutdown()

Shuts down all clustered services.

static NamedCache getCache(String cache)

Returns an instance of a cache. Either joins an existing cache in the cluster or creates the cache if this is the first member.


For a full list of methods in the NamedCache interface and the CacheFactory class, see the Javadoc in C:\oracle\product\coherence\doc.

3.2 Creating Your First Coherence-Based Java Program

This section describes how to create a Java program that allows you to access, update, and remove simple types of information from a Coherence clustered cache.

  1. Create a Program to Put Values in the Cache

  2. Create a Program to Get Values from the Cache

3.2.1 Create a Program to Put Values in the Cache

Follow these steps to create a Coherence Java-based application.

  1. Create a new project in JDeveloper. Name the project InsertValue. Ensure that directory is C:\home\oracle\labs\InsertValue.

    See "Creating a New Project in an Existing Application" if you need detailed instructions.

  2. Check the Libraries and Classpath value under Project Properties for the Coherence entry. Ensure that the full path is provided for the coherence.jar: C:\oracle\product\coherence\lib\coherence.jar

  3. Create your first Coherence Java program. Name the class MyFirstSample and select the Main Method check box.

    See "Creating a Java Class" if you need detailed information.

  4. In the JDeveloper editor, write the code to create a NamedCache, put in a value, and then verify the value that you put in. Save the file after you finish coding. Example 3-1 illustrates a sample program.

    Example 3-1 Creating a NamedCache; Inserting and Verifying Values

    package com.oracle.handson;
    
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    
    public class MyFirstSample {
        public MyFirstSample() {
        }
    
        public static void main(String[] args) {
            
           // create or get a named cache called mycache 
           NamedCache myCache = CacheFactory.getCache("mycache");
           
           // put key, value pair into the cache. 
           myCache.put("Name","Gene Smith");
            
           System.out.println("Value in cache is " + myCache.get("Name"));
            
        }
    }
    
  5. Stop any running cache servers.

  6. Run the program in JDeveloper: right-click the MyFirstSample.java class in the editor and choose Run.

  7. You should see messages similar to the following:

    Figure 3-1 Output for Creating a NamedCache and Storing and Retrieving Values

    Creating a NamedCache and Storing and Retrieving Values

3.2.2 Create a Program to Get Values from the Cache

Follow these steps to create a Java class which gets the value from your cache, instead of doing a put and then a get.

  1. Create another Java class named MyFirstSampleReader. See "Creating a Java Class" if you need detailed information. Example 3-2 illustrates a sample program.

    Example 3-2 Getting a Value from the Cache

    package com.oracle.handson;
    
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    
    public class MyFirstSampleReader {
        
        public MyFirstSampleReader() {
        }
    
        public static void main(String[] args) {
            // ensure we are in a cluser
            CacheFactory.ensureCluster();
             
            // create or get a named cache called mycache 
            NamedCache myCache = CacheFactory.getCache("mycache");
                    
            System.out.println("Value in cache is " + myCache.get("Name"));
        }
    }
    
  2. Run the MyFirstSampleReader class. Figure 3-2 illustrates the output from the program. Note that a null value is returned. Although MyFirstSample successfully created and populated the NamedCache, the cache only existed within the MyFirstSample process memory. When MyFirstSample terminated so did the cache.

    Figure 3-2 Output from the Sample Reader Program

    Output from the SampleReader Program
  3. Start the cache-server.cmd that you used in "Testing a Coherence Installation", run MyFirstSample to put the value in the NamedCache, and then run MyFirstSampleReader to read the value from the cache. Note the output illustrated in Figure 3-3: the "Gene Smith" value stored by MyFirstSample is returned by MyFirstSampleReader.

    Figure 3-3 Output from the Sample Reader Program with a Running Cache Server

    SampleReader Program Output with Running Cache Server

    This should not be the case for a process that joins the cluster only to perform an operation, such as putting in a value and then leaving, like MyFirstSample. By default, all processes start as storage-enabled. The process can store data as part of the cluster. You must modify the process so that it is not storage-enabled. Use the following Java command-line parameter.

    -Dtangosol.coherence.distributed.localstorage=false
    

    The Java option -Dtangosol.coherence.distributed.localstorage specifies whether a process is storage-enabled. Setting the parameter to false specifies that the process is not storage-enabled.

    1. Change the project properties to disable local storage. See "Changing Project Properties, Setting Runtime Configuration" for detailed information.

    2. Enter the following value in the Java Options field:

      -Dtangosol.coherence.distributed.localstorage=false -Dtangosol.coherence.log.level=3
      

      The Java property tangosol.coherence.log.level=level changes the level of logging produced by Coherence. The level can be set to a number between 0 and 9. The default is 5. A value of 0 means no logging., while a value of 9 means extremely verbose. A value of 3 is often useful enough for most application development.

  4. Shut down any running cache servers and rerun your MyFirstSample class.

    You receive a message similar to the one in Figure 3-4 indicating that storage is not enabled on the cluster, because you have set this member to be storage-disabled.

    Figure 3-4 Output from JDeveloper if Storage is Disabled

    Output from JDeveloper if storage is disabled.
  5. Restart the cache server and run MyFirstSample and MyFirstSampleReader again. You should now see that the data is persisted between running the two Java examples.

3.3 Creating Your First Coherence-Based Java Application

In this exercise, you develop a simple Java console-based application to access, update, and remove simple types of information from a Coherence clustered cache.

This exercise assumes you have completed "Testing a Coherence Installation". Make sure you have a cache server and a cache client running.

Unlike client/server applications, in which client applications typically "connect" and "disconnect" from a server application, Coherence-based clustered applications simply ensure they are in a cluster, after which they may use the services of the cluster. Coherence-based applications typically do not "connect" to a cluster of applications; they become part of the cluster.

  1. Create the Console Application

  2. Run the Console Application

3.3.1 Create the Console Application

To create a Java console-based application to access, update, and remove simple types of information from a Coherence clustered cache:

  1. Examine the methods in the CacheFactory class using the Coherence Java documentation (Javadoc) that is shipped in the C:\oracle\product\coherence\doc directory.

  2. Develop a simple Java console application (Java class) called YourFirstCoherenceApplication that uses the CacheFactory class to join a cluster (using the ensureCluster method), and then leave the cluster (using the shutdown method). See "Creating a Java Class" if you need detailed information on creating a Java class.

  3. Examine the methods that are available in the NamedCache interface using the Javadoc.

  4. Extend your application to use the CacheFactory method getCache to acquire a NamedCache for the cache called mycache (the same cache name used in the exercise: "Testing a Coherence Installation").

  5. With the NamedCache instance, use the "get" method to retrieve the value for the key "message" (the same key used in the exercise: "Testing a Coherence Installation").

  6. Output the value to the standard out using the System.out.println(….) method.

    Example 3-3 illustrates a sample Coherence-based Java application:

    Example 3-3 Sample Coherence-Based Java Application

    package com.oracle.handson;
    
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    
    public class YourFirstCoherenceApplication {
    public YourFirstCoherenceApplication() {
    }
    
       public static void main(String[] args) {
    
          CacheFactory.ensureCluster();
    
          NamedCache myCache = CacheFactory.getCache("mycache");
    
          String message = (String)myCache.get("message");
    
          System.out.println(message);
    
          CacheFactory.shutdown();
    YourFirstCoherenceApplication yourfirstcoherenceapplication = new YourFirstCoherenceApplication(); 
       }
    
    }
    

3.3.2 Run the Console Application

Follow these steps to run the Coherence application.

  1. Ensure that you have the Coherence cache server and cache client running. In the cache client, connect to the mycache cache. For example:

    Map(?): cache mycache
    
  2. Execute YourFirstCoherenceApplication from the JDeveloper IDE and view the result.

    Figure 3-5 illustrates the output from YourFirstCoherenceApplication. The output indicates that there is no data in the cache for the message key.

    Figure 3-5 Output from Coherence-Based Java Application: No Value for the Key

    Coherence-Based Java Application Output: No Data in Cache
  3. Using the running cache client, change the key "message." For example, enter

    Map <mycache>: put message "hello"
    

    Rerun YourFirstCoherenceApplication from the JDeveloper IDE to see the changed values. Figure 3-6 illustrates that the cache now holds the value hello for the key message.

    Figure 3-6 Output from Coherence-Based Java Application: A Data Value for the Key

    Coherence-Based Java Application Output: Data Value in Cache
  4. Rerun YourFirstCoherenceApplication with the following JVM parameter. Notice that the output is the same as the previous run.

    -Dtangosol.coherence.distributed.localstorage=false
    
  5. Shut down your cache server and cache client instances. Restart the cache server and then rerun YourFirstCoherenceApplication (with the preceding JVM parameter set). Note the output is now null.

  6. If you change the value of the message key in your application (using the put method), is the new value available through the cache client?

    1. For example, comment out the get method and add the put method.

      //String message = (String)myCache.get("message");
        String message = (String)myCache.put("message", "bye");
      
    2. Run YourFirstCoherenceApplication.

    3. Run the get command in the cache client.

      Map (mycache): get message
      

      You should see bye as the output.