Build your own
caching mechanisms with volatile
collections - JavaWorld June 1999
Tutorial Details:
Build your own caching mechanisms with volatile collections
Build your own caching mechanisms with volatile collections
By: By Thomas E. Davis
This month's tool -- a self-cleaning hashtable -- is great for implementing caching in your Java applications
he literal definition of the word volatile is "readily vaporizable," with a secondary connotation of "changeable." This month's tool matches this description nicely, as its implementation will cause the objects contained in a hashtable to vaporize, and the rate of that vaporization is indeed changeable.
But more on that in a moment. First, I'll address reader feedback from last month's column .
Reflections
Half a dozen readers wrote in to inform me that the following block of code (which relates to the GlobalValues tool we discussed two columns back ) is a performance bottleneck for multithreaded access.
public static synchronized GlobalValues getRef() {
if( self == null )
self = new GlobalValues();
return self;
}
Synchronization is only necessary for the part of the method that instantiates a new instance of the GlobalValues . This will happen the first time the method is called. The block of code should therefore only synchronize if it needs to perform instantiation, as follows:
public static GlobalValues instance() {
if( self == null ) {
synchronized( GlobalValues.class ) {
if( self == null ) {
self = new GlobalValues();
}
}
}
return self;
}
And that's it. No other problems came to my attention this month. ( Whew! ) On to this month's topic.
The concept of caching
Caching is a time-honored method for improving the performance of an application. Instead of constantly creating and destroying objects as needed, a cache holds on to them and reuses them when appropriate. The Web browser you're running right now uses caching in a number of ways. For example, the JavaWorld logo at the top of this page appears at the top of all the articles. But your browser doesn't reload the image as you travel from one article to the next. The browser caches the image and reuses it when needed.
However, the browser can't cache the image forever. The more sites you visit, the more images the browser saves, and soon you run out of hard drive space. So, the caching mechanism in your browser has to perform some garbage collection. The browser basically sets a maximum space limit for caching images and destroys the oldest images in the cache when that limit is reached.
Caching in Java
In Java, it's incredibly simple to implement a crude caching mechanism using the Hashtable class. Here's how: When you (or your application) need an object, first check to see if it's in the Hashtable . If the required object isn't there, create a new instance of it and put it into the Hashtable . This way, the next time you need it, it's right where you left it.
The tricky part is the cleanup. At some point, your application needs to go through the Hashtable and clean up the objects that haven't been used for a while and are wasting memory. Where do you put this cleanup code? How often do you call it? These are problematic issues, but what if you had a special instance of the Hashtable that knew how to clean itself up? Hello Cachetable !
Ping -- the Cachetable's friendly reminder
The magic behind the Cachetable is a timer thread that periodically reminds the table to clean itself up. I've dubbed this tool Ping . In the olden days of submarine warfare, when a sub was looking for a target it would send out an audible ping sound. This sound would then bounce back from any obstruction, thus revealing the position of the target. In the wonderful land of Unix and the Internet, there exists a little utility called ping that is used to the same effect. The Unix utility sends out a packet to its "target" machine and if the target machine is up and running it "bounces" the packet back.
My Ping utility follows the same traditional concept. Ping sleeps for a predetermined amount of time, then "pings" a target object. How the target object handles the ping depends on the implementation. All that is required is for the target object to implement the Pingable interface. Implementing the Pingable interface forces the target class to implement the ping() method. The ping() method will be called at a regular interval (further explained below):
public interface Pingable
{
public void ping();
}
Implementing the Ping thread is now incredibly simple. The constructor takes two arguments: the target object and the time (in milliseconds) to sleep between pings, as shown below:
public class Ping extends Thread
{
private long sleepTime;
private Pingable target;
public Ping( Pingable target, long sleepTime ) {
this.target = target;
this.sleepTime = sleepTime;
}
The run() method of Ping loops infinitely between sleeping and pinging:
public void run() {
while( true ) {
try {
sleep( sleepTime );
} catch( InterruptedException e ) {
// ignore it!
}
target.ping();
}
}
}
So far, so simple, right?
The TimeWrapper
Properly cleaning up the contents of the cache requires that each object's age be tracked. For this task, we'll use another little tool, which I call TimeWrapper . The TimeWrapper simply stores an object and a timestamp. The constructor takes an object and internally sets the timestamp to the current time. Here's the first part of the TimeWrapper class, which implements these concepts:
public class TimeWrapper {
private long age;
private Object object;
public TimeWrapper( Object object ) {
this.object = object;
updateAge();
}
private void updateAge() {
age = System.currentTimeMillis();
}
The wrapper then exposes two accessor methods -- one to retrieve the contained object and another to get the age of the object. Notice that the getObject() method updates the age of the object. When we ask for the age of the contents, we want to know how long it has been since the last time they were accessed. Here are those accessor methods (and the last part of the TimeWrapper
class):
public long getAge() {
return( System.currentTimeMillis() - age );
}
public Object getObject() {
updateAge();
return( object );
}
}
The Cachetable object
The Cachetable object extends a Hashtable and implements the Pingable interface. The Cachetable 's implementation of the ping() method will check the age of each contained object (via the TimeWrapper , explained below) and simply vaporize any stale objects. Here's the first part of the tool:
import java.util.Hashtable;
import java.util.Enumeration;
public class CacheTable extends Hashtable implements Pingable {
The constructor takes the desired expiration time for objects stored in the underlying Hashtable , and starts up an instance of the Ping tool:
private long expireTime;
private Ping cleaner;
public CacheTable( long expireTime ) {
super();
this.expireTime = expireTime;
cleaner = new Ping( this, ( ( long )( expireTime * 0.75 ) ) );
cleaner.start();
}
To keep track of the age of the objects in the Hashtable , we wrap them in a TimeWrapper . To do this, we must override the get() and put() methods.
When an object is placed into the Cachetable , the key is preserved but the object itself is wrapped in a new instance of TimeWrapper .
public synchronized Object put( Object key, Object value ) {
return( super.put( key, new TimeWrapper( value ) ) );
}
When an object is retrieved from the Cachetable , it must also be extracted from its TimeWrapper encasement. As explained above, the TimeWrapper updates the age of the object when the object is extracted:
public synchronized Object get( Object key ) {
return( ( (TimeWrapper) super.get( key ) ).getObject() );
}
When the Ping instance calls the ping() method within the Cachetable , the table performs the actual cleanup. It cycles through all the objects in the table and examines their TimeWrapper s. If an object hasn't been accessed via a get() call within the expiration time specified, it's removed from the Hashtable (and garbage-collected if no other threads retain a handle to it). Here's the implementation of the ping() method and the cleanup logic:
public synchronized void ping() {
Enumeration e = super.keys();
while( e.hasMoreElements() ) {
Object key = e.nextElement();
TimeWrapper tw = (TimeWrapper) super.get( key );
if( ( tw != null ) && ( tw.getAge() > expireTime ) ) {
remove( key );
}
}
System.gc();
}
}
Notice that we used super.get() to access the TimeWrapper object. If we had called get() , the instance defined by the subclass would be invoked and we would have received the raw object instead of the wrapper. Also note that we call the Java garbage collector at the end of the method. This is just a trigger to the virtual machine, requesting that it reclaim memory at the next available opportunity.
Conclusion
The Cachetable tool is a clean and simple way to implement caching in your Java applications. I'm sure you'll also find uses for the Ping and TimeWrapper tools. Your homework assignment is to implement a volatile "queue" using the techniques and tools discussed in this article. I'll be using such a queue in an upcoming installment of Cool Tools . As always, comments, criticisms, and especially design-improvement suggestions are welcome.
This page formated for crawlers and browsers that don't support scripts and tables.
Home
EZone
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Build your own
caching mechanisms with volatile
collections - JavaWorld June 1999
View Tutorial: Build your own
caching mechanisms with volatile
collections - JavaWorld June 1999
Related
Tutorials:
|
Displaying 1 - 50 of about 2121 Related Tutorials.
|
Create Your Own Package
Create Your Own Package
Create Your Own Package
  |
Example -- drawHouse
Java: Example -- drawHouse
Java NotesExample -- drawHouse
This example shows how to build our own... to a layout.
4 * @version 22 June 1998, revised July 1999, 2002-02-07 JPanel
5 |
Eclipse Plunging-Build and Deploy
OpenMake Mojo is the ultimate tool for managing your build and release... software builds. Meister allows you to dramatically decrease your build times by supporting "build avoidance" for building Jars. You can bring your Continuous |
Mojo - Free Build to Release
Mojo - Free Build to Release
Mojo - Free Build... is the only tool you will ever need for automating, centralizing and accelerating your software development processes from build to release. ?
Mojo |
Collections (Data Structure Library)
, ...) or your own class.
Wrapper classes are immutable, which may...
Collections (Data Structure Library)
Collections (Data Structure Library)
Predefined |
Java Data Structures
write your own
Most data structure textbooks give students the impression... of your own data structures,
but you can program faster, and produce more... (somewhat more convenient in Java 5),
use alternate libraries,
or write your own |
Collections Framework
developers the
following benefits:
It increases the readability of your collections... offers the highest performance for your purposes.
Interfaces of the collections...
Collections Framework
Collections Framework |
Decreasing process time by caching through the Hash Table in Java
Decreasing process time by caching through the Hash
Table in Java
Decreasing process time by caching through the Hash
Table in Java... of any type of the operation performed by your java program. You can easily |
Watch Out For Spyware Programs That Slows Down Your Computer System
Watch Out For Spyware Programs That Slows Down Your Computer System... Your Computer System
 ...;
Syd Johnson
Spyware is a program that once loaded on your computer |
Collections Overview
Java: Collections Overview
Java NotesCollections Overview
Summary of Collections interfaces
Most...
that the classes implement.
Collections - This is a basic set of methods for working |
Java 5 Features
Java Notes: Java 5 Features
What's new in Java 5
Java Collections have....
The concurrent collections can be executed by more than one thread without blocking....
Example using Java 1.2-1.4 data structures
// Typical Collections usage |
Watch Out For Spyware Programs That Slows Down Your Computer System
Watch Out For Spyware Programs That Slows Down Your Computer System... Your Computer System
 ...;
Syd Johnson
Spyware is a program that once loaded on your computer |
Apache Ant - Building Simple Java Projects
learn how to use Ant to build his/her own java projects;
and if you are already... is a mean to build java projects. Ant is an open source tool
that is easy to use... installing it on your system to how to run and use it -
every aspect |
Collections Class
Java: Collections Class... utility methods
for manipulating collections.
Some useful Collections methods...
using Comparator comp.
There are many more methods in Collections |
For-each Loop
implement Iterable<E> for your own data structures.
General Form... in Java 5 to make iteration
over arrays and other collections more convenient...
in a collection of values.
Arrays and Collections.
It's commonly used to iterate over |
Developing Search Engine in Java
develop your own search engine for your website in Java
technologies. We... or a Web Crawler which fetches web pages in a methodical manner and build... are developing is power full engine that you can use on
your website |
GUI Alternatives
have to use the
Java GUI libraries to build your GUI..., it isn't difficult to build a Graphical User Interface (GUI) in Java... should your interface be in Java? You can use existing GUI technologies
like |
Sorting Arrays
Java: Sorting Arrays
Java NotesSorting Arrays
Why you shouldn't write your own sort
A favorite... of the
java.util.Arrays.sort() methods; they do not write their own,
except perhaps in unusual |
Writing your First WAP Application.
write your own scripts...Writing your First WAP Application.
function validateForm... your |
Introduction to Collections Framework
Introduction to Collections Framework, Advantages and Disadvantages of the Collection Framework
Introduction to Collections...;
Collections Framework:
The Collections |
Working with java Collections class
Working with java Collections class
Working with java Collections class
 ... to wok with
Collections class of java.util package. Actually java collections |
Java Server Faces (JSF)
to
build rapid data-driven Java web applications.
To make efficient... the JSF form validation framework.
To explore how to make your
own custom JSF components.
To learn techniques for converting |
VOIP for Your Business
VOIP for Your Business
VOIP for Your Business... is a standard open protocol, businesses can easily integrate their own audio... where VoIP can help.
If your business is expanding and you need a larger |
What would you rate as your greatest weaknesses?
What would you rate as your greatest weaknesses?
What would you rate as your greatest weaknesses?
 ... weakness, you will be respected for your honesty, but your resume will end up |
Java Notes: Downcasting
Java Notes: Downcasting
Collections of Objects - The Dark Side
There are a lot of things to like about Java Collections, but there are some
weak aspects too.
Slow - No primitives. The elements of all Collections data |
JDO Implementations
;
To build application using Java JDO technology, we need..., SQL, or JPQL, and comes with its own byte-code enhancer. JPOX is available under... persistence engine. Kodo allows your team to focus on creating value-added business logic |
Prepare Success Stories for Your Interview
the strategy behind those answers and then give a response in your own words. More important, be prepared with stories of your own that support your answer.
Why... these are just your own stories- thus they help you to stand out from the crowd |
Quiz Extreme
;
Use Quiz Extreme quiz software to make your own quizzes
on any subject, using... own quizzes with little effort or time.
Build quizzes from my own mix....
Assess my children's progress.
School Teachers
Create my own quizzes |
I Terribly Wrong In Your Computer
I Terribly Wrong In Your Computer
I Terribly Wrong In Your Computer
 ... Terribly Wrong In Your Computer
This really chapped my lips...Spy |
How to Backup Your Computer Files
How to Backup Your Computer Files
How to Backup Your Computer Files
 ... we need most. Consider this: When was the last time you backed up your computer |
Common concerns to build a project
concerns to build a project
 ... time resources, classes, and project dependencies.
3.
The build output: Developers spend a good chunk of time in creating build scripts such
as ANT |
Introduction to Maven 2
. Several projects were there containing
their own slightly different Ant build files...;
Maven2 is an Open Source build tool that made the
revolution in the area of building projects. Like the build systems as "make" |
Is Your Web Browser Putting You At Risk
Is Your Web Browser Putting You At Risk
Is Your Web Browser Putting You At Risk... Internet Explorer, youre right on the money. So, is your web browser putting you |
Open Source Build Tools written in Java
|
Your suggestions
Your suggestions
 ...;
Use the form on this page to tell us your ideas...:
Your name |
Open Source Open Source Java Collections API written in Java
|
Log4E-Code Management
logging framework. Thus you might be able to
adapt to your own logger by defining your own templates using the preferences.
It has active support for Log4j, Commons...;
Log4E is an Eclipse
Plugin which helps you to use your |
We would like to hear about your goals.
?
This is an easy question if you are prepared for it. Present your own ideas....
Avoid bringing up salary on your own-let the interviewer do it first...
We would like to hear about your goals.
We would like |
Java Notes: Tools
Notes: Tools
You need software tools to build Java programs.
Unless otherwise... Compiler
This is an open-source Java compiler. It shouldn't be your first... it
can increase your programming productivity, and because it's
a useful |
Introduction to Collections API
About Collections,Collection Java,Collection API,Introduction to Collections API
Introduction to Collections API...;
As
the name indicates, collections
is a group of objects known as its |
Your competitor presses you to reveal some confidential information about your current or previous employer.
their own employees to behave while talking with their competitors.
Whenever your own...
Situation: Your competitor presses you to reveal some confidential information about your current or previous employer.
Situation |
CAP - Code Analysis Plugin
and analysis
the dependencies of your Java project. It opens a own perspective... the weaknesses in your architektur, will help
to improve the encapsulation. As a result your |
I think you should be earning more money at this point of your career. Why isn?t it happening?
achievements and teachings. Be clear on how these have inspired your own achievements...)
I think you should be earning more money at this point of your career. Why... might use it as a trap while negotiating your salary. However your answer should |
Ant Custom Properties
;
Setting properties in the build file is the first method of providing
custom properties with <property> element in an ant build...
target has been selected. You can also set properties at the beginning of a
build |
Open Source Java Collections API written in Java
|
Collections Exercise 3 - Points
Java: Collections Exercise 3 - Points
Java: Collections Exercise 3 - Points
Name ____________________________________
For the purposes of this exercise, the only data structures |
Net caboodle plugin
for you to develop MIDP clients for your
business services, without the need to write any of your own protocol code. The
plugin generates MIDP 'stubs' for your... connecting your
mobile to your PC webcam with Whoosh Cam which is a free service |
Download security software
the open ports on your system and what programs own
them. It also includes many...; Protect your system and other security
programs from attacks by other |
Collections Framework Enhancements
Collections Framework Enhancementsin Java SE 6,SE 6, SE6 Collections
Collections Framework Enhancements
  |
Java example program to get IP address of own system
java example program to get IP address of own system
Java example program to get IP address of own system... get own IP address
An IP (Internet Protocol) address is a numerical unique |
|
|
|