Monday, November 30, 2009

Working with JCS


Step 1: Core Concepts
Before using JCS, you must know some basic terms used in JCS like elements, region, auxiliaries.
Elements are the objects you put in cache. Objects are retrieved using a key, much like hashtable.
You can think of JCS as a collection of hashtables that you reference by a name. Each of these hashtables is called a Region. Each of the region can be configured independently from each other.
Auxiliaries are optional plugins that a region can use. The core auxiliaries are the Indexed Disk Cache, the TCP Lateral Cache, and the Remote Cache Server. The Disk Cache, for example, allows you to swap items onto disk when a memory threshold is reached.
Step 2: Downloading JCS and required dependencies
As of version 1.2.7.0, the core of JCS requires only two other jars.
commons-logging
Versions 1.2.6.9 and below also require the following two additional jars:
commons-collections
commons-lang
Step 3: Configuring JCS
Following is the configuration for a sample program.
# CACHE REGIONS AVAILABLE
# DEFAULT CACHE REGION

# sets the default aux value for any non configured caches
jcs.default=DC
jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MaxObjects=1000

# Regions preconfigured for caching
jcs.region.bookCache=DC
jcs.region.bookCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
jcs.region.bookCache.cacheattributes.MaxObjects=1200
jcs.region.bookCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
jcs.region.bookCache.elementattributes.IsEternal=false
jcs.region.bookCache.elementattributes.MaxLifeSeconds=7200
jcs.region.bookCache.elementattributes.IdleTime=1800
jcs.region.bookCache.elementattributes.IsSpool=true
jcs.region.bookCache.elementattributes.IsRemote=false
jcs.region.bookCache.elementattributes.IsLateral=true

# Primary Disk Cache -- faster than the rest because of memory key storage
jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory
jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes
jcs.auxiliary.DC.attributes.DiskPath=/usr/opt/bookstore/raf
jcs.auxiliary.DC.attributes.MaxPurgatorySize=10000
jcs.auxiliary.DC.attributes.MaxKeySize=10000
jcs.auxiliary.DC.attributes.OptimizeAtRemoveCount=300000
jcs.auxiliary.DC.attributes.MaxRecycleBinSize=7500

Provide at least one region and one auxiliary configuration.
Step 4: Examples
We have a Book java POJO class. This is the object we are interested to put in cache. The Book class must implement Serializable interface.  This is required as JCS uses Disk Swap once max. object limit is reached.
class Book implements Serializable {
      private String bookName;
      private String author;
      private String isbn;
     
      public String getBookName() {
            return bookName;
      }

      public void setBookName(String bookName) {
            this.bookName = bookName;
      }

      public String getAuthor() {
            return author;
      }

      public void setAuthor(String author) {
            this.author = author;
      }

      public String getIsbn() {
            return isbn;
      }

      public void setIsbn(String isbn) {
            this.isbn = isbn;
      }

      public Book(String bookName, String author, String isbn){
            this.bookName = bookName;
            this.author = author;
            this.isbn = isbn;
      }
     
      public Book(){
           
      }
}
Now we have to create a cache instance and put the Book objects in cache.  This is pretty easy, similar to putting and retrieving objects from Hashtable.
public class JCSExample {

      private static JCS bookCache;
      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            Book javaBook = new Book("Complete Reference Java", "Herbert Schildt", "1234");
            Book oracleBook = new Book("Oracle 10g", "Oracle Press", "1235");
            Book unixBook = new Book("Advanced Unix", "Linus", "1236");
           
            try {
                  bookCache = JCS.getInstance("bookCache1");
            } catch (CacheException e) {
                  // TODO Auto-generated catch block
                  System.out.println("Cannot create cache.");
                  e.printStackTrace();
            }
           
            try {
                  System.out.println("Inserting JavaBook in cache");
                  bookCache.put("JavaBook", javaBook);
                  System.out.println("Inserting OracleBook in cache");
                  bookCache.put("OracleBook",oracleBook);
                  System.out.println("Inserting UnixBook in cache");
                  bookCache.put("UnixBook", unixBook);
            } catch (CacheException e1) {
                  // TODO Auto-generated catch block
                  System.out.println("Could not insert into cache.");
                  e1.printStackTrace();
                  System.out.println(e1.getMessage());
                  System.exit(0);
            }
           
            Book book = new Book();
            book = (Book) bookCache.get("JavaBook");
            System.out.println("The Book name is - "+book.getBookName());
            book = (Book) bookCache.get("OracleBook");
            System.out.println("The Book name is - "+book.getBookName());
            book = (Book) bookCache.get("UnixBook");
            System.out.println("The Book name is - "+book.getBookName());
            System.out.println(bookCache.getStats());
            try {
                  bookCache.clear();
                  bookCache.dispose();
            } catch (CacheException e) {
                  // TODO Auto-generated catch block
                  System.out.println("Could not clear cache");
                  e.printStackTrace();
            }
      }
}

The program above is pretty straightforward. The best part of using JCS is, it’s simple to use.
Next post I will discuss about the Ehcache.

Thursday, November 26, 2009

Caching Objects

Cache is a duplicate set of data, stored at some temporary location in order to help application fast access to it. Caching is used to minimize the IO or Database read operations. Objects which are used very often are stored in cache. Using cache significantly improves application’s performance. Examples of objects eligible for cache are, objects in a drop down list, most frequently searched/ reviewed books on an e-commerce site etc.
Here I am referring to Java caching. There are many cache options available for Java developers. I have considered two of them for comparison - JCS and EHCache.
Java Caching System (JCS)
·         Object cache
·         Open-source
·         Freely available
·         Easy to use and configure
·         Configurations made through cahce.ccf file
·         Can’t use for non-serializable objects in cache
·         Always uses Disk Swap, if maximum object limit is reached i.e objects are written to a disk location after maximum limit is reached.
·         Addition and retrieval is straightforward.
EHCache
·         Java distributed cache for general purpose caching, Java EE and light-weight containers 
·         Open-source
·         Covered under Apache Open Source License
·         Provides way to handle non-serializable objects caching
·          Configurations made through an xml file
·         Can create listeners for Add/Remove event on cache
·         Inserting and retrieval from Cache is little complex
Based on these points, first decide which cache is suitable to you. We will discuss each of the two caches in detail.

Thursday, September 24, 2009

Enabling debugging on Apache tomcat server

Often it is difficult to debug an application deployed on server. So SOP are added in methods.
However this is possible with Apache Tomcat. Add following line to catalina.bat and startup.bat files,

set JPDA_TRANSPORT=dt_socket
set JPDA_ADDRESS=8000

After setting these properties, restart the tomcat server.

Go to Run -> Debug Configuration and choose Remote Java Application.
Set up a new configuration with host as localhost and port as JPDA_ADDRESSc i.e 8000.
Click Debug.

This will start a Remote VM debug session which runs in background. Then run your program and the control will enter the breakpoint set by you.

Happy Debugging..!!

Tuesday, September 22, 2009

Spring: java.lang.NoSuchField error : ruleMemo

The error is caused by org.antlr.runtime.BaseRecognizer class. The original antlr distribution, which comes along with standard Apache Ant distribution does not contain a field called ruleMemo in BaseRecognizer class. So if you have original antlr jar used in your application you are likely to encounter this error.
To resolve the error get the latest com.springsource.org.antlr jar from spring framework website. Spring has included the missing field in BaseRecognizer class. Include this jar in your applications lib directory and you are all set to run your spring application

Sending SQL query output to a txt file

To send output of a sql query to a text file use following commands,

spool c:emp.txt
/
select * from emp
/
spool off;

This will write all rows returned by query to emp.txt