JAVA AND
CACHING
By Martin Nad
6/26/2009
[email protected]
Java and cashing
Java and caching
[TYPE THE SUBTITLE]
OVERVIEW
Here I want to show why and you should use cache, and
presents some different kind of caching system in java, and
give you an example by on chaching system.
Page 2
Java and cashing
TABLE OF CONTEXT
Foreword
Caching
Different kind of caching in java
ehCache example
Page 3
Java and cashing
FORWORD
When we are working with the large information and retrieve
too much information or data, we need a mechanism to get
retrieve faster information.
Caching is one way to optimize the access time to retrieve
information.
Especially when we use the database, and we have too much
traffic between database and application, we can use caching
to reduce the traffic to the database.
If we use the third-party application to get data, we can also
use caching here to reduce traffic and save lot of the time.
Usually, the third-party application is outside of the local
network, and it takes more time to get data from third-party
application. And certainly, they use some database too. There
are many different situation that you can use caching and you
shouldn’t use caching in all cases either.
Here I will discuss about general caching and how to use it in
your application and with the database and using with the
Hibernate.
Page 4
Java and cashing
CACHING
Caching system is a smart way to reduce the response time of
your application.
You can use caching in different area, in your application, in
your database level, or using cache with the Hibernate
If you use hibernate, hibernate uses two differ nets caching
level.
1-first level cache
2-second level cache
A discussion I had with one of my colleges, I told him,
Hibernate reduce the database-connection and database
traffic, and he was against to it, and he told he has test and
checked the database log and noticed that the database
connection was extremely high with hibernate. It sounds odd.
And it doesn’t agree with any documentation and books that I
have read. I believe he had some configuration-problem with
his hibernate.
It is not important which tools, technology or method you are
using, it is most important you use those tools, technology or
method, in right way. Not just use Hibernate, because
everybody talks about it, or if it is poplar and so on. If you
don’t know how you can use the Hibernate, it should cost you
much more time and resource. Even I think it is very easy to
use. Maintains of it, update your application all of them cost
time. Especially if you use the tools in wrong way, it should
Page 5
Java and cashing
cost you much more. I have noticed it in almost my
documentation about it.
Anyway, the first level cache is using by Session object.
Hibernate use this level as cache as default. It will reduce the
number of sql-queries.
One example: if you use several update with the same
transaction, hibernate will just update once for all modification
at the end of the transaction.
And the second level cache is using by Session Factory object.
This kind is very interesting. This level of cache is available for
the whole of application and it will return the object or an
object that already is/are loaded on the cache. Any
transaction is definitely avoided.
DIFFERNET KIND OF CACHING PACKAGES
We have at least 4 different caching packages:
1-EhCache: http://ehcache.sourceforge.net/
It is used widely in the J2EE and light-weight application
Some advantages of EhCache are:
1-it is fast
2-easy to use
3- it has support all, memory or disc caching
4- it has support read-only, read/write caching
But it hasn’t support clustering-cache system
Page 6
Java and cashing
2- OsCache: http://www.opensymphony.com/oscache/
It is used to generate dynamically jsp-pages and it
includes the jsp-library.
You can use it in the large system.
Some advantages:
- It has support all, memory, disc and some basic
support for clustering-cache system by using JMS,
JavaGroup.
- It has upport for read-only, read/write caching
3- SwarmCache: http://swarmcache.sourceforge.net/
It has simple support for clustering cache system.
It has support for read-only, read/write caching
It is very good to use this caching-method when you have
many read operation than write operation.
4-Jboss TreeCache
Page 7
Java and cashing
WHAT YOU SHOULD THINK FOR IMPLEMENTATE A CACHING
SYSTEM
Caching planning:
As you can see there are different caching packages that you
can use them on what you want to do
We have at least 4 different caching plan:
1-read only; as you can guess this plan is good if you have
just data that it doesn’t ever change. You can use Ehcache or
OsCache
2- read/write: in this case the data needs to update,
frequently. You can EhCache or OsCache
3-nonStrick read/write. It doesn’t guaranty that any update
shouldn’t take place more than once. You can use
SwarmCache
4-transactional caching plan. You can use this plan for JTA
(Java transactional API). You can use Jobs treeCache
Page 8
Java and cashing
EHCACHE EXAMPLE
I will here give two example of using eHcache. One in java
main, the second with servlet.
To using Ehcache, you need a configuration file, which here I
call it ehcache.xml. There you can define your caching policy
as well as:
maxElementsInMemory
eternal
timeToIdleSeconds
timeToLiveSeconds
and so on.
The configuration file can look like this:
<ehcache>
<diskStore path="java.io.tmpdir"/>
Page 9
Java and cashing
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
/>
</ehcache>
And maybe you want to have a bean as follows.
package martin.nad.cache.ehcache.exampel1;
import java.io.Serializable;
public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name = "";
private String address = "";
public Customer () {
// Default constructor.
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
Page 10
Java and cashing
public void setName(String name) {
this.name = name;
}
}
And your main class:
package martin.nad.cache.ehcache.exampel1;
/**
*
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import net.sf.ehcache.*;
public class App
Page 11
Java and cashing
{
public static void main( String[] args )
{
App app = new App();
try {
app.manager =
CacheManager.create("c:/tmp/enCache.xml");
System.out.println("manager
is...."+app.manager);
app.cache =
app.manager.getCache("sampleCache1");
} catch (Exception e) {
System.out.println(e);
}
read_writeInCache();
public void destroy() {
}
Page 12
Java and cashing
protected void read_writeInCache() {
Customer mycustomer = new Customer ();
mycustomer.setName("Martin Nad");
mycustomer.setAddress("my address");
// Caching this element
Element element = new
Element(mycustomer.getName(), mycustomer);
System.out.println("element is: "+element);
System.out.println(this.cache);
cache.put(element);
// Reading the cache
try {
element = cache.get("Martin Nad");
} catch (Exception e) {}
Page 13
Java and cashing
Customer my2customer =
(Customer)element.getValue();
System.out.println("Cache loaded ");
System.out.println("Name : " +
my2customer.getName() );
System.out.println("address : " +
my2customer.getAddress() );
}
private CacheManager manager = null;
private Cache cache = null;
And just run, and you are done with your first caching-
system.
If you want use in your servlet, your servlet can look like:
Page 14
Java and cashing
package martin.nad.cache.ehcache.exampel1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import net.sf.ehcache.*;
public class servletEhcacheExample1 extends HttpServlet {
private static Logger logger =
Logger.getLogger(servletEhcacheExample1.class.getName());
private CacheManager manager = null;
Page 15
Java and cashing
private Cache cache = null;
public void init() throws ServletException {
PropertyConfigurator.configure( getServletContext().getRealP
ath ("WEB-INF/log4j.properties") );
try {
manager =
CacheManager.create(getServletContext().getRealPath
("WEB-INF/ehCache.xml"));
cache = manager.getCache("sampleCache1");
} catch (Exception e) {
logger.error("Unable to load EHCACHE
configuration file");
}
public void destroy() {}
Page 16
Java and cashing
protected void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
doGet(req, res);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out = response.getWriter();
Customer myCustomer = new Customer ();
myCustomer.setName("Martin Nad");
myCustomer.setAddress("some address");
Element element = new
Element(myCustomer.getName(), myCustomer);
cache.put(element);
// Reading the cache
try {
Page 17
Java and cashing
element = cache.get("Martin Nad");
} catch (Exception e) {}
Customer myNewCustomer =
(Customer)element.getValue();
out.println("Name : " +
myNewCustomer.getName() +"<br/>");
out.println("Address : " +
myNewCustomer.getAddress() +"<br/>");
}
}
Page 18
Java and cashing
OPEN SYMPHONY CACHING
OSCACHE
DONATION
If you like this documentation and it was
helpful you can just donate 7$ by using this
https://www.paypal.com/cgi-bin/webscr?cmd=_s-
or use this to put
xclick&hosted_button_id=5814019
any amont you like to donate
https://www.paypal.com/cgi-bin/webscr?cmd=_s-
xclick&hosted_button_id=5813954 and if it doesn’t work copy
the link and put it on your browser.
if it doesn’t work copy the link and put it on your browser.
MY OTHER PAPERS
Properties in Java and Spring by Martin Nad
Spring and Cxf by Example
Jboss and Perm Gen Error
Using Ftp Service With Spring
JunIt
How to use Maven
ReFactoring
Page 19
Java and cashing
Maven and Custome Archetype
How to Write Effective Code
Using Generic in Java Why and where
Java Caching
what is new in java 5
Page 20