Wednesday, March 26, 2014

How to put and get some data from Oracle Coherence Cache? Basic code snippets of Oracle Coherence

package javaapp;

import com.tangosol.coherence.transaction.OptimisticNamedCache;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
public class CoherenceClient {
    public static void main(String[] args) {
        CacheFactory.ensureCluster();
        // Get an instance of the coherence cache
        NamedCache cache = CacheFactory.getCache("hello-example");
       
        // Put some elements into cache
        putElementsinCoherence(cache);
       
        // Print all the existing elements in the coherence cache
        printCohrenceCacheElements(cache);
        removeAllElementsFromCoherenceCache(cache);
       
        // Destroy the cache
        cache.destroy();
       
        // Try to print the elements in the c
        printCohrenceCacheElements(cache);
        CacheFactory.shutdown();
    }
   
    public static void putElementsinCoherence(NamedCache cache) {
            for(int i=0;i <10; i++) {
                // Put some dummy elements in the cache
                cache.put(i, "Vinay " + i);
        }
    }

    public static void printCohrenceCacheElements(NamedCache cache) {
        // Check if the cache is active
        if(cache.isActive()) {
            System.out.println("Printing all the elements of " + cache.getCacheName());
            for(Object key : cache.keySet()) {
                // Print the elements fromt he cache
                System.out.println((String)cache.get(key));
            }      
           
        }
    }

    public static void removeAllElementsFromCoherenceCache(NamedCache cache) {
        // Remove all the elements from the cache
        cache.clear();
    }
}

No comments:

Post a Comment