Thursday, March 23, 2006

Singleton Pattern in Java

It is an interesting fact that people still consider double checked locking as a valid and the best way to implement Singletons in Java. A recent discussion with one of my peers brought this to my notice and hence I take this chance to describe the different implementations of singletons in Java and their drawbacks (or point to the right resources).
Singletons can be implemented in Java in multiple ways. Each implementation guarantees a single instance (not considering serialization and extension, which have to be handled anyway), but vary in thread safety.


Implement a synchronized getInstance() method. This method can be seen in
listing 1. Though this method guarantees a singleton and is thread safe,
it comes with the overhead of synchronization. Each call to getInstance()
carries the overhead synchronization.
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// Make it private to avoid instantiation.
public synchronized static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
return instance;

Listing 1: Singleton implementation with synchronized getInstance()


In order to minimize synchronization overhead, double checked locking method has
been suggested. This method can be seen in the listing 2. Here the a
synchronized block is entered only when instance is null, which occurs when the first thread (or set of threads simultaneously) enters the getInstance() method. Although this method is more efficient, it may fail to be thread-safe when used with an optimizing compiler, as described in Double checked locking and the Singleton Pattern. Many different variants of this implementation have been suggested and disproved. One of the variants (using volatile instance) of double checked locking implementation of the singleton pattern can be used successfully in Java 5 because of the changes made in JSR 133, but it does not add much to performance over the synchronized implementation. This is because, with the changes made to the Java memory model in JSR 133, the cost of using volatile is comparable to that of synchronizing.
class Singleton {
private static Singleton instance = null;

public Singleton getInstance() {
if (instance == null) {
synchronized {
if (instance == null)
instance = new Singleton();
return instance;

Listing 2: Singleton implementation with double checked locking.


The best way to implement singletons in Java is to initialize the static
instance variable with it's declaration
or initializing the instance variable from within a static initialization block. This implementation can be seen in listing 3.

private static class Singleton{
public static Singleton instance = new Singleton();

private Singleton() {

public static Singleton getInstance() {
return instance;

Listing 3: Singleton with static variable initialization.

This implementation is thread-safe because, the Java language specification (8.3.2 Initialization of fields) guarantees that the static member variables will be initialized exactly once.
If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized.

Friday, March 17, 2006

Java Memory leaks

Memory leaks were and are a serious concern for Java programmers. Though garbage collection helps avoid many causes of memory leaks in other languages (like unfreed pointers of C/C++), Java programs have some sources of memory leaks. The root cause of memory leaks in Java is any program that holds a reference to an object that will not be used anymore. Although such memory leaks are undetected in small programs, they will be more visible in applications that run on a server for a long/indefinite time. Another case is when native code (written in C/C++) invoked from Java (through the Java Native Interface) does not release system resources. This is because the the Java garbage collector does not collect the memory held by C pointers (Conservative garbage collection). It is hard to identify if your Java application has memory leaks by simply looking at the code as they show up only in runtime. The hint of a memory leak is the java.lang.OutOfMemoryError (This does not necessarily mean a memory leak, you may simple need more memory to run your application). I tried to list out a few causes of memory leaks in Java applications and some recommendations based on my experience and with the help of a few articles that I listed at the bottom:

ResultSet and Statement Objects
JDBC ResultSet and Statement objects will be closed when the connection that created them is closed. However, while using pooled connections, if close() is invoked on the connection, the connection will be returned to the connection pool rather than being closed. Consequently, the ResultSet and Statement objects created by the connection will not be closed automatically, and are a potential cause of memory leaks.

Explicitly close all ResultSet and Statement objects created using pooled connections. It is also a good practice to explicitly close ResultSet and Statement objects as this will release any resources held by these objects.

Collection Objects
A Java collection holds references to other objects. It grows as elements are added to it. While the collection itself has a longer lifetime, individual elements within it do not. Hence, if the individual collection elements are not removed, the collection can grow indefinitely, and the JVM could run out of memory. Also known as Lapsed listeners since they are most commonly observed in event listeners held in collections.

Explicitly remove objects from collections if they will not be used anymore. Weak references may also solve the problem in some cases. Using weak references to plug Java memory leaks is discussed in : Java theory and practice: Plugging memory leaks with weak references. An example of using the WeakHashMap is also provided in the article.

Static classes and singletons
Static variables and classes, once loaded, will exist through out the lifetime of the application. The same is the case with Singleton objects. If there are too many singletons/static classes in the application, the available memory in the JVM will be significantly decreased for the rest of the application's lifetime. In this case it is the classloader that becomes too large. The proliferation of singletons antipattern addresses this specific issue. A similar problem is incorrect scoping. If you have an variable that might only be needed within a single method as a member variable of a class, then the variable effectively has the same lifetime as the class.

Avoid creating too many singletons. Too many is a relative term and is dependent on your application requirements and memory availability.

Data stored in the HttpSession will be available till the user logs out. Storing too much data in the HttpSession will quickly lead to OutOfMemoryError. Another problem is when persistent session are used, then the servlet may need to serialize/deserialize the objects stored in the session and this adds a significant overhead in case of large objects.

Use HttpRequest to transfer data whenever possible instead of HttpSession. If the objects have to be available for longer time, then they can be moved to the business layer. Elements in the session must be explicitly removed Java memory leaks -- Catch me if you can

Caching can play a significant part in Java memory leaks. It is similar to HttpSession usage, but outside the scope the Web tier. Too little caching will not give the expected performance boost, while too much caching may hamper performance by taking up a lot of memory.

There are a lot of sophisticated caching frameworks available (open source and commercial) which handle the memory efficiently. These frameworks come to use if you have an application that is heavily dependent on caching. A cheaper way of caching would be to use soft references, they are more suited for simpler caching requirements.

To summarize, the following is quick list of the sources of memory leaks in Java applications:
  • ResultSet and Statement Objects
  • Static classes and singletons
  • Incorrect Scoping
  • HttpSession
  • Caching
How Do You Plug Java Memory Leaks?
Plug memory leaks in enterprise Java applications
Java theory and practice: Plugging memory leaks with soft references

Tuesday, March 14, 2006

Oracle SQL Developer: Free Database Development Tool

Oracle announced the general availability of Oracle(r) SQL developer, a new, free, database developement tool. Oracle SQL developer simplifies development cycles and reduces the need to buy third-party tools for developing and debugging SQL and PL/SQL code. The Oracle SQL developer product is developed in Java and hence runs on Windows, Linux and Mac OS X. SQL developer can be installed on the Database Server and developers can connect remotely from their workstations. Oracle SQL developer offfers features to assist developers perform tasks such as
  • Object browsing and creation
  • Running SQL statements and SQL scripts
  • Editing and debugging PL/SQL code
  • Viewing and updating data
  • Allows deveopers to build custom reports.
  • Includes a code formatter and code snippets.
This tool is available for Oracle 10g and Oracle 9i database release 2. You can download Oracle SQL developer here. An Online help document [PDF] is also provided. A 5 step tutorial to connect to Oracle XE is provided on the site.

Monday, March 13, 2006

Java based blog server

Roller is a Java based blog server. It is in Apache incubator as of now. Roller drives Sun Microsystem's employee blogging site, the Javalobby's JRoller Java community site, and hundreds of other sites. If you want to set up a blog server for yourself or for several thousand of your closest friends, then Roller is the perfect choice. Roller supports most of the common weblogging features such as
  • Group blogging
  • RSS and ATOM feeds
  • Rich-text editing
  • Customizable tamplates
  • Comment Management and Moderation
  • Trackbacks with verification
  • Referrers
  • Blogroll management
  • XML-RPC interface for blogging clients such as ECTO, MarsEdit and w:bloggar.
  • Security is implemented using Acegi security.
  • Includes a pluggable and configurable LRU cache, which can be monitored using the Cache Info page.
A project Wiki is also available.

Friday, March 10, 2006

Apache Shale Web Framework

Apache Shale is a Java Server Faces based Web Application Framework from the Apache software foundation. Shale is talked of as the "heir" Apache struts framework. We all know that struts is the most used Java Web Framework so far. While shale is the successor of Struts, there is a significant departure of architecture from sturts to shale. Firstly, while struts is based on a monolithic Request Processor, Shale is set of fine-grained services that can be combined as needed to meet particular application needs. Secondly, while sturts can be integrated with Java Server Faces, Shale is built upon JSF. The major features of the Shale Framework are:
  1. View Controller - Convenient mechanism to associate a "backing" Java class with each JavaServer Faces view (a JSF WebPage) in an application, with predefined event handers for events significant to an application developer.
  2. Dialog Manager - Mechanism to define a "conversation" with a user that requires multiple HTTP requests to implement, modeled as a state diagram.
  3. Application Manager - Traditional application wide front controller features that should be applied to every request.
  4. Validation - Integration with the Jakarta Commons Validator Framework, supporting both client side and server side validations based on a single set of configured validation rules.
  5. Remoting - Server side support for applications that employ AJAX (Asynchronous JavaScript and XML) style interactions.
  6. Spring Integration - Integration with the Spring Framework, allowing the use of Spring's dependency injection framework to create JavaServer Faces managed beans.
  7. Clay - An alternative to JSP where you define views in pure HTML, in a fashion similar to Tapestry and Facelets. An innovative sub-framework for supporting the configuration of reusable subtrees of JavaServer Faces components for customizable reuse.
  8. Test Framework - Set of mock objects and JUnit test case base classes suitable for testing both the framework classes themselves, as well as application components built on top of the framework.
  9. Java 5 Extensions - Optional add-on library that adds additional ease-of-use features for Shale applications that run on Java Standard Edition 5 (popularly known by its code name during development, "tiger").
  1. The Shale home page
  2. Integrate Struts and JSF

Thursday, March 09, 2006

JBoss Cache

JBoss has released the a Beta version of JBoss cache 1.3. JBoss cache is designed to run on any J2SE environment. Here is a list of features offered by JBoss cache:
  • Optimistic node locking
  • Invalidation instead of replication
  • Improved CacheLoader performance
  • Ability to ‘chain’ more than one CacheLoader
  • A new ‘Options’ API, allowing configuration overriding on a per-invocation basis
  • A new ‘ClusterCacheLoader’ that treats a remotely running caches in the same cluster as a cache loader source
  • JDBCCacheLoader with improved compatibility with MySQL JDBC drivers
  • Replication performance enhancements with JGroups 2.2.9
Supports three scenarios:
  • Local cache, without any replication.
  • Replicated cache, using non-blocking, asynchronous replication.
  • Replicated cache, using blocking, synchronous replication.
Caching in JBoss cache seems to lean toward AOP and hence, I am will not get into that, just yet.

Wednesday, March 08, 2006

Java Object Caching with WebSphere Dynamic Caching

The Dynamic cache service of WebSphere Application Server works within the server Java Virtual Machine. The advantage of using WebSphere for caching is that the cache distribution will be handled by the application server. The WebSphere Dynamic Cache can be used to cache servlets, WebSphere Commands, Web Services and - through the DistributedMap and DistributedObjectCache interfaces - the Java Objects from within J2EE applications on the server. Our focus here is on caching Java Objects from within J2EE applications. The DistributedMap and DistributedObjectCache interfaces provide simple interfaces for interacting with dynamic cache.In order to handle updates and invalidations, WebSphere allows you to declare dependencies on other objects. Element grouping may thus be achieved based on the element
dependencies. WebSphere Application Server also offers a Web Application called Cache Monitor, which plugs into the cache to provide a view of its contents and statistics. The dynamic cache uses the
Least Recently Used (LRU) algorithm to create space for incoming entries. Dynamic cache can also be configured to push data to a disk cache when assigned memory is full. Dynamic cache can take advantage of
WebSphere Data Replication Service (DRS) to replicate cache in a
  1. Dependencies: A feature of WebSphere Application Server V6.
  2. Element grouping: Element grouping through dependencies.
  3. Configurable runtime parameters: Can be configured in file or using WebSphere Application Server Administrative console.
  4. Security: The cache instances will be available as JNDI resources in the server. Hence they will be accessible to all the applications running on the server. Cache instances can only be protected by securing the JNDI resources.
  5. Region data separation and configuration: Cache elements have to be separated into different cache instances.
  6. Element event handling: Applications may define invalidation listeners and change listeners.
  7. Fine grained element configuration options: Dynamic Cache service provides API to control the configuration options at individual element level. This can be achieved through the following put method in the DistributedMap interface.
Relevant links:
  1. WebSphere Dynamic Cache: Improving J2EE application performance [PDF] [HTML]
  2. WebSphere V6 Information Center: Dynamic Caching

Tuesday, March 07, 2006

Java Object Caching with EHCACHE

EHCache is a pure Java, in-process cache available on Source-Forge. It is the default pluggable cache for Hibernate 3.0. In light of the fact that support for Java Caching System is being removed from Hibernate, EHCache gains some extra notice. EHCache supports Less Frequently Used (LFU), First-In-First-Out (FIFO) algorithms in addition to Least Recently Used (LRU) algorithm for cache eviction. The following types of cache stores are supported in EHCache:
  • Memory cache
  • Disk Cache
  • Distributed cache
The following description of the features in EHCache that meet our requirements
  • Dependencies: For JDK1.4, JDK1.5 and JDK 1.6, EHCache requires commons-logging and commons-collections 2.1.1 from Apache's Jakarta project.
  • Element grouping: Element grouping is not supported in EHCache. The only level of grouping allowed in EHCache is at the cache level. A single cache manager can manage multiple caches.
  • Data Expiration: Data expiration can be set declaratively as well as programmatically at the cache level. EHCache does not provide support for setting expiration values at the element level.
  • Configurable runtime properties: Runtime parameters can be configured in the xml file, which can be defined externally. The XML file has to conform to the schema defined in the ehcache.xsd. The properties that can be configured at the region level include maximum objects, cache name, size, shrink interval etc.
  • Element event handling: EHCache allows to attach event handlers to the cache manager (cache add, remove) and the cache (put, update, remove).
I did not provide any code samples here because the invocation is quite straight forward and the configuration values are similar to that of Java Caching System except that they will be defined in XML instead of property file. All the documentation for EHCACHE is found in one place.

Monday, March 06, 2006

Java Object Caching with Java Caching System

Java Caching System is a distributed caching system written in Java. In this post I discuss the basic overview of how to use JCS and point to the relevant parts of the documentation of the product for further information. Most of the information has been gathered and organized from the site. The foundation of JCS is the composite cache.Four types of caches can be plugged into the Composite Cache for any given region:
  • LRU Memory Cache: An extremely fast, highly configurable memory cache. It uses the Least recently used algorithm to manage the number of items that can be stored in the cache.
  • Indexed disk cache: Fast, reliable and highly configurable swap for cached data. Cache elements are written to disk via a continuous queue-based process. Every aspect fo the disk cache is configurable, and a thread pool can be used to reduce the number of queue worker threads across the system.
  • TCP Lateral cache: Provides an easy way to distribute cache data into multiple servers. Uses a UDP discovery mechanism so that the entire farm need not be reconfigured when a new node is added. Each node maintains a connection to every other. TCP lateral can be configured to change most interactions each node has with it's peers.
  • RMI Remote cache: A remote cache server can be configured as a central connection point for all the nodes instead of each maintaining a connection with the every other node. The remote server broadcasts events (updates, invalidations etc.) generated on one node to the others. The remote cache server holds a serialized version of your objects, so it does not need to be deployed with your class libraries.
Writing code for the Java Caching system is quite simple.

import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;
. . .
private static final String cacheRegionName = "city";
private JCS cache = null;
. . .
// in your constructor you might do this
try {
setCache( JCS.getInstance( this.getCacheRegionName() ) );
} catch ( CacheException e ) {
log.error( "Problem initializing cache for region name ["
+ this.getCacheRegionName() + "].", e );
. . .
// to get a city out of the cache by id you might do this:
String key = "cityId:" + String.valueOf( id );
City city = (City) cache.get( key );
. . .
// to put a city object in the cache, you could do this:
try {
// if it isn't null, insert it
if ( city != null ) {
cache.put( key, city );
} catch ( CacheException e ) {
log.error( "Problem putting "
+ city + " in the cache, for key " + key, e );
The following is a small description of how the requirements that I outlined in the caching requirements post can be implemented using JCS.
  • Dependencies: As of version, the core of JCS (the LRU memory cache, the indexed disk cache, the TCP lateral, and the RMI remote server) requires only two other jars.
    • concurrent
    • commons-logging
    Versions and below also require the following two additional jars:
    • commons-collections
    • commons-lang
  • Element grouping:The JCS provides feature rich grouping mechanism, where groups of elements can be invalidated and whose attributes can be listed.
  • Data expiration: Data expiration can be controlled at the individual element level. This can be achieved declaratively as well as programmatically. In order to declare the expiration charecteristics within a region, add the following under the region definition.


    This applies to all elements within a region and if declared in the defaults, will apply to elements in all regions.
    In order to programmatically set the expiration properties, then you can do so using IElementAttributes as shown below:
    // jcs.getDefaultElementAttributes returns a copy not a reference
    IElementAttributes attributes = jcs.getDefaultElementAttributes();
    // set some special value
    attributes.setIsEternal( true );
    jcs.setDefaultElementAttributes( attributes );

  • Configurable runtime parameters: Runtime parameters can be configured in the cache.ccf file. The parameter that can be configured at the element level are discussed in the element sections. The configuration properties that can be set at the region level are discusses here. The properties that can be configured at the region level include maximun objects, cache name, size, shrink interval etc. An example is shown below

  • Disk overflow (and defragmentation)
    Thread pool controls
    Region data separation and configuration

    More information on configuring auxilaries can be found on the site as they have extensive configurable properties.
  • Element event handling: JCS allows to attach event handlers to elements in the local memory cache (does not work for auxilaries, i.e. lateral, remote and disk caches). To create an event handler you must implement the org.apache.jcs.engine.control.event.behavior.IElementEventHandler interface. This interface contains only one method:
    public void handleElementEvent( IElementEvent event );

    The IElementEvent object contains both the event code and the source. The source is the element for which the event occurred. Once you have an ElementEventHandler implementation, you can attach it to an element via the Element Attributes as shown below
    MyEventHandler meh = new MyEventHandler();
    // jcs.getDefaultElementAttributes returns a copy not a reference
    IElementAttributes attributes = jcs.getDefaultElementAttributes();
    attributes.addElementEventHandler( meh );
    jcs.put( "key", "data", attributes );
  • Fine grained element configuration options: As discussed above.
  • Non-blocking "zombie" (balking facade) pattern:
    Lateral distribution of elements via HTTP, TCP, or UDP
    UDP Discovery of other caches

    JCS uses the zombie pattern in the Lateral TCP Cache auxilary. More information may be found here.
  • Remote synchronization
    Remote store recovery
    Remote server chaining (or clustering) and failover
    Information about the configuration options for clustering can be found at Remote auxilary caching

Friday, March 03, 2006

Free Database Versions: IBM, Oracle and Microsoft

Oracle announced the general availability of the free version (Oracle 10g Express edition) of their database product following microsoft(SQL Server Express edition) and IBM (DB2 Express-C). This product supports Oracle Call Interface for C and C++, Oracle HTML DB, ODBC, Oracle Data Provider for .NET, OLE DB, JDBC, and PHP development environments. The following are a few features of the product:
  1. Available on 32-bit Linux and Windows Installs using native installers
  2. English (single byte character set) and International (Unicode) versions available with support for 10 major languages
  3. Supports up to 4GB of user data
  4. May be installed on a server with any amount of memory, but will only use up to 1GB RAM of available memory
  5. Fully upgradeable to other Oracle Database 10g editions
  6. Oracle Text for efficient text-based searches
An Oracle Java developer's guide is also provided along with an Oracle 10g express edition getting started guide. Although all three come with a free to develop, deploy and distribute licenses, they have a few restrictions. The following is a list of restrictions for the free version of databases provided by IBM, Microsoft and Oracle.
Oracle 10g Express edition
  • Processors: Can be installed on multiple CPU Server but will use only ONE CPU.
  • Memory: A maximum of 1GB memory will be used (Even if you have more).
  • Database size: Up to 4GB user data.
Microsoft SQL Server Express edition
  • Processors: 1 CPU, but can be installed on any server
  • Memory: 1 gigabyte (GB) addressable RAM
  • Database Size: 4 GB maximum database size
IBM DB2 Express-C
  • Processors:Upto 2 dual-core processors.
  • Memory: A maximum of 4GB addressable memory.
  • Database Size: Unlimited
Looking at this, if you are planning on using a free database for you application, it looks like DB2 Express-C is the clear will with respect to database size and memory availability.

Thursday, March 02, 2006

Java Object Caching: Requirements

This is a follow-up of the Java Object Caching post that was posted on March 1st. As mentioned earlier, Object Caching refers to caching objects that are neither fully static not fully dynamic. There are a few Object Caching services available under the Apache License, and are quite easy to plug into your applications. The following is a list of features that may be available in a caching service, which can be used as a guide for determining the right requirements of a caching tool for your needs:
  1. Minimal dependencies
  2. Element grouping
  3. Quick nested categorical removal
  4. Data expiration: idle time, max life
  5. Configurable runtime parameters
  6. Security: Authentication or authorization should be completed before objects return from the cache. The information transmitted between caches should be encrypted.
  7. Disk overflow (and defragmentation)
  8. Thread pool controls
  9. Region data separation and configuration
  10. Element event handling
  11. Fine grained element configuration options
  12. Remote synchronization
  13. Remote store recovery
  14. Scheduled cache expiry
  15. Non-blocking "zombie" (balking facade) pattern: When using distributed caching, Puts and removals are queued and occur asynchronously in the background, and hence are non-blocking. Get requests are synchronous and can potentially block if there is a communication problem.
  16. Lateral distribution of elements via HTTP, TCP, or UDP
  17. UDP Discovery of other caches
  18. Remote server chaining (or clustering) and failover
  19. Reliability
  20. Maintainability
These are a few general issues when considering caching services. The specific application may have a superset or a subset or a combination with other requirements.

Yahoo Design Patterns Library

This has been around for a while but I just came across , but in case you haven't seen it and you're doing web-based development, you really should check out the Yahoo Design Patterns Library. It is a part of the Yahoo! developer network (something really new to me, as I did not go to yahoo for a while). It's simply an excellent resource for web developers. I just went through a part of the site and here is a part of some interesting stuff going on in the yahoo developer network ...
  1. The JavaScript developer center: This section provides a lot of articles and documentation on how to use JavaScript with yahoo! products and services and also many code samples you can learn (wink, wink) from and make use of in your own web and client applications.
  2. The UI Library: The Yahoo! User Interface Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, HTML and AJAX. All the components in the Yahoo! User Interface Library have been released as open source under a BSD license and are free for all uses.
  3. The Widget engine: The Yahoo! Widget Engine (formerly known as Konfabulator) is a JavaScript runtime engine for Windows and Mac OS X, which help you create widgets for your desktop such as clocks, calculators, stock tickers etc.
  4. Maps API: There are three API families for Yahoo! maps - AJAX, Flash, and the original Simple API.
  5. The PHP developer center: As you might have known, Yahoo! runs PHP, and naturally have a PHP developer center where they provide HOWTO articles, code samples, and community resources for using Yahoo! Web services with PHP.
This is but a very small part of their developer center. You can access a host of other REST based web services for almost all their products, including flickr, etc. The Yahoo! web services blog provides up-to-date information of the services provided by yahoo. The Yahoo! developer community section contains links to sample applications implemented by other Yahooo! developers and also support groups for each of the product web service sections.

Wednesday, March 01, 2006

WebSphere Application Server Security Flash

WebSphere Application Server Support has issued a security flash: Security: Possible security exposure with JSP source code on IBM WebSphere Application Server Version 5 (PK13792 and PK20181) here are the details:
Under some circumstances, the JavaServer Pages (JSP) source code is returned instead of the formatted output.
Affected versions: WAS 5.0.2.x and 5.1.1.x
Does not affect WAS 6.x

Interim Fixes have been released for the affected versions.
Interim Fix PK13792 (PK13792_50210_50215.jar) - For WebSphere Application Server 5.0.2.x
Interim Fix PK13792 (PK13792_5114_5118.jar) - For WebSphere Application Server 5.1.1 cumulative fix 4 through cumulative fix 8.
Interim Fix PK20181 (PK20181_5119.jar) - For WebSphere Application Server 5.1.1 cumulative fix 9.

These fixes will be rolled into the next cumulative release. The future cumulative fixes for the affected product versions will include these fixes.

To get notified of announcements like this in the future, subscribe to IBM's RSS feed for WAS.

Java Object Caching:

Object caching is an important aspect in the design and development of Web Applications. Object caching is for objects which are neither static (unchanging) nor fully dynamic. The best definition of object caching can be found in the functional specification document for Object Caching Service for Java OCS4J, which says ...
A server must manage information and executable objects that fall into three basic categories: objects that never change, objects that are different with every request, and everything in between. Java is well equipped to handle the first two cases but offers little help for the third. If the object never changes, we create a static object when the server is initialized. If the object is unique to every request, we create a new object each time. For everything in between, objects or information that can change and are shared across requests, between users or between processes, there is the "Object Caching Service."
Object Caching appears to be similar to object pooling in many ways but, the difference is that pooled objects don't have any identity. While in case of pooling, we are looking for any object, possibly within certain characteristic constraints, in case of caching we are looking for a specific object with an identity and probably a state. The only purpose of object pooling is to prevent memory allocation. While object caching help improve application performance and scalability, it has some cost associated with it.
  1. Consistency: Depending on the type of data that is being cached, the caching mechanism has to ensure consistency between the original and cached objects.
  2. Durability: Changes made to the cache are likely to be lost (System cache).
  3. Size: The memory used by cached objects needs to be maintained at a reasonable amount as is the case with HTTPSession too.
So how would you decide what objects to cache and what should not be cached. The following simple rules may be used as a guide.
Which objects may be Cached: Any data that does not change frequently and takes longer times to retrieve from the data source is a good candidate for caching.
What not to cache:
  1. Secure information that can be accessed by other users on the web site. Like User profile information and other personal information, or credit card details.
  2. Business information that changes frequently and causes problems if not up to date and accurate.

Popular Posts