Caching mechanism of Ibatis

Source: Internet
Author: User
Tags java reference

Cache
Caching is often the most critical factor for improving system performance on a specific hardware basis (assuming that the system does not have design gaps and bad inefficient SQL statements).
Relative to the more tightly packaged ORM implementations such as hibernate (because the operation of the data object is more tightly encapsulated, it can guarantee the cache synchronization within its scope, and Ibatis provides a semi-closed encapsulation implementation, so it is difficult to fully automate synchronization of the cache operation).
The Ibatis caching mechanism must be used with special care. In particular, the Flushonexecute setting takes into account all operations that may cause actual data to be inconsistent with the cached data. such as the other statement in this module to update the data, other modules of the data updates, and even third-party systems to update the data. Otherwise, the appearance of dirty data will cause great danger to the normal operation of the system.
It is recommended that you avoid the blind use of the cache if you cannot fully determine the extent of the data update operation.
In combination with Cachemodel view:
<cachemodel
Id= "Product-cache"
Type = "LRU"
Readonly= "true"
Serialize= "false" >
</cacheModel>

As you can see, the cache has several more important properties:
ReadOnly
Serialize
Type

ReadOnly
The ReadOnly value is whether the data object in the cache is read-only. The read-only does not mean that data objects can no longer be modified once they are placed in the cache. Instead, when the data object changes, such as a property of the data object changes, the data object will be abolished from the cache, the next time you need to re-read the data from the database to construct a new data object.
The readonly= "false" means that the data objects in the cache can be updated, such as the Name property of the user object is changed.
Read-only caches provide higher read performance, but are less efficient once the data has changed. System design should be based on the actual situation of the system (the probability of data update) to determine the cache read and write policy.
Serialize
If a global data cache is required, the Serialize property of the Cachemodel must be set to true. Otherwise, the data cache is valid only for the current session (which can be understood simply as the current thread), and the local cache has limited overall performance gains for the system.
In the case of serialize= "true", if more than one session reads a data object from the cache at the same time, the cache will return a copy of the object for each session, that is, each session will have a different object instance containing the same information. Thus the session can access the data it obtains from the cache without worrying about synchronization conflicts in multi-threaded concurrency scenarios.
Cache Type:
Like Hibernate, the Ibatis is implemented via a plug-in implementation of the buffer interface, which provides a variety of cache implementation mechanisms to choose from:
1. MEMORY
2. Lru
3. Fifo
4. Oscache

Memory type cache and WeakReference
The cache implementation of the MEMORY type is actually done through a Java object reference. In Ibatis, its implementation class is Com.ibatis.db.sqlmap.cache.memory.memorycachecontroller,memorycachecontroller Internally, a hashmap is used to hold a reference to the data object that currently needs to be cached.
It is important to note that there are three kinds of object reference relationships in JAVA2:
A SoftReference
b weakreference
C Phantomreference

Traditional Java object references, such as:
public void dosomething () {
User user = new user ()
......
}

When the DoSomething method ends, the reference to the user object is lost, and the memory space it occupies is reclaimed by the JVM at the next garbage collection. If we save a reference to the user object in a global HashMap, such as:
Map map = new HashMap ();
public void dosomething () {
User user = new user ();
Map.put ("user", user);
}

At this point, the user object has saved the reference in the map, so long as the reference exists, the JVM will never reclaim the memory that the user object occupies.
This memory management mechanism is believed to be familiar to all of you, and in most cases it is almost a perfect solution. But in some cases, it's a little inconvenient. For the cache here, when the user object is used, we want to keep its reference for reuse the next time it is needed, but do not want this reference to persist for a long time, and if the reference to each object is preserved for long periods, The limited memory space will be consumed immediately by this data. The best way to do this is to have a reference that can still access the object until the object has been reclaimed by the garbage collector, and when the garbage collector starts, it is routinely recycled if it is not used by other objects.
SoftReference, WeakReference, phantomreference for the above ideas to provide a strong support.
These three types of references are "non-persistent references", meaning that the referential relationship does not persist, and the reference life cycle that they represent is closely related to the operation of the JVM, rather than relying on the pre-planning of the coding phase as in the case of a reference in the traditional sense.
Let's look at a softreference example:
SoftReference ref;
public void dosomething () {
User user = new user ();
ref = new SoftReference (user);
}
public void doanotherthing () {
User user = (user) ref.get ();//Get object reference by SoftReference
System.out.println (User.getname ());
}

Suppose we first executed the DoSomething method, produced a user object, and created a softreference reference for it.
At some point, we call the Doanotherthing method and get a reference to the user object through SoftReference.
Can we still get a reference to the user object at this point? This depends on the operation of the JVM. For SoftReference, the JVM will reclaim its included references only if it is currently out of memory (the JVM does not start the garbage collection mechanism only when memory is low, and when it is garbage collected depends on the garbage collection policy of each version of the JVM. If the garbage collection strategy is: When the system is currently more idle, and invalid objects to a certain rate of start garbage collection mechanism, at this time the free memory may be more abundant). There are two possible scenarios, namely:
? The JVM has not yet experienced garbage collection due to insufficient memory, and references to user objects can be recovered from the JVM heap by SoftReference.
? The JVM has started a garbage collection mechanism because of insufficient memory, and the references to the user objects contained by SoftReference are discarded by the JVM. At this point the Ref.get method returns a null reference (NULL), which means that a nullpointerexception may be thrown in the code above.
WeakReference is weaker than softreference in terms of the sustainability of the reference. There is no need to wait for out-of-memory situations, so long as the JVM starts the garbage collection mechanism, the WeakReference object will be reclaimed by the JVM.
In other words, the probability of weakreference being recycled by the JVM is greater relative to softreference. Phantomreference is less sustainable than weakreference. Unlike WeakReference and SoftReference, the objects referenced by Phantomreference can hardly be reused by recycling. The object it points to has actually been destroyed by the JVM (the Finalize method has been executed), but it has not been recovered by the garbage collector for the time being.
Phantomreference is mainly used for the destruction process of auxiliary object, which is seldom involved in the development of practical application layer.
The memory-type cache is implemented with SoftReference, WeakReference, and, in general, Java reference, to manage the caching of objects.
The following is a typical memory type cache configuration:
<cachemodel id= "User_cache" type= "MEMORY" >
<flushinterval hours= "/>"
<flushonexecute statement= "UpdateUser"/>
<property name= "Reference-type" value= "WEAK"/>
</cacheModel>

Where flushinterval specifies how long to clear the cache, the previous example specifies that all contents of the buffer are forcibly emptied every 24 hours.
The Reference-type property can be configured in the following ways:
1. Strong
This is based on the traditional Java object reference mechanism, unless the cache is explicitly emptied (such as the time set by Flushinterval, the method specified by the Flushonexecute is executed, or the cache is cleared by the code, etc.), otherwise the reference is persisted.
This type of setting is useful for caching commonly used data objects, or for situations where the current system memory is very abundant.
2. SOFT
Based on the SoftReference cache implementation, the data objects in the buffer pool are recycled only when the JVM is running out of memory.
This type of setting is suitable for situations where the system memory is more abundant and the system concurrency is relatively stable.
3. WEAK
Based on the WeakReference cache implementation, when the JVM is garbage collected, the data objects in the cache are reclaimed by the JVM.
In general, the weak memory-type cache configuration can be used.

LRU Type Cache
When the cache reaches its pre-set maximum capacity, Ibatis will purge the least frequently used objects from the buffer in accordance with the "least-used" principle.
<cachemodel id= "Usercache" type= "LRU" >
<flushinterval hours= "/>"
<flushonexecute statement= "UpdateUser"/>
<property name= "Size" value= "$"/>
</cacheModel>

The configurable parameters are:
U flushinterval
Specifies how long to clear the cache, and the previous example specifies that all contents of the buffer are forcibly emptied every 24 hours.
U size
The maximum capacity of the cache.
FIFO type cache
FIFO cache, the data that is first placed in the cache is first abolished. The configurable parameters are the same as the LRU type:
<cachemodel id= "Usercache" type= "FIFO" >
<flushinterval hours= "/>"
<flushonexecute statement= "UpdateUser"/>
<property name= "Size" value= "$"/>
</cacheModel>

Oscache
Unlike the above several types of caches, Oscache comes from a third-party organization, Opensymphony. The latest version of Oscache (http://www.opensymphony.com/oscache/) can be obtained from the following URLs. In the production deployment, it is recommended that Oscache,oscache is a widely used open source cache implementation (which also provides support for Oscache in Hibernate), based on a more reliable and efficient design, and more importantly,
The latest version of Oscache already supports the cache cluster. If the system needs to be deployed in a cluster, or if it needs to be deployed in a multi-machine load-balancing mode to gain performance benefits, then Oscache is the perfect place to be.
The configuration for Oscache in Ibatis is fairly straightforward:
<cachemodel id= "Usercache" type= "Oscache" >
<flushinterval hours= "/>"
<flushonexecute statement= "UpdateUser"/>
<property name= "Size" value= "$"/>
</cacheModel>

The reason why the configuration is simple is that Oscache has its own configuration file (oscache.properties) J.
The following is a typical Oscache configuration file:
#是否使用内存作为缓存空间
Cache.memory=true
#缓存管理事件监听器, this listener tells you how the current cache is running
Cache.event.listeners=com.opensymphony.oscache.plugins.clustersupport.jmsbroa
Dcastinglistener
#如果使用磁盘缓存 (Cache.memory=false), you need to specify the disk storage interface implementation
#cache. Persistence.class=com.opensymphony.oscache.plugins.diskpersistence.disk
Persistencelistener
# The file storage path used by the disk cache
# Cache.path=c:\\myapp\\cache
# Cache scheduling algorithm with optional Lru,fifo and infinite cache (Unlimitedcache)
IBATIS Developer ' s Guide Version 1.0
September 2, 2004 so many open source projects. Why isn't Open your Documents?
# Cache.algorithm=com.opensymphony.oscache.base.algorithm.fifocache
# Cache.algorithm=com.opensymphony.oscache.base.algorithm.unlimitedcache
Cache.algorithm=com.opensymphony.oscache.base.algorithm.lrucache
#内存缓存的最大容量
cache.capacity=1000
# whether to limit the capacity of the disk cache
# Cache.unlimited.disk=false
# JMS-based cluster cache synchronization configuration
#cache. cluster.jms.topic.factory=java:comp/env/jms/topicconnectionfactory
#cache. Cluster.jms.topic.name=java:comp/env/jms/oscachetopic
#cache. Cluster.jms.node.name=node1
# Javagroup-based cluster cache synchronization configuration
#cache. CLUSTER.PROPERTIES=UDP (Mcast_addr=231.12.21.132;mcast_port=45566;ip_
ttl=32;mcast_send_buf_size=150000;mcast_recv_buf_size=80000):P ing (timeout
=2000;num_initial_members=3): MERGE2 (min_interval=5000;max_interval=10000
): Fd_sock:verify_suspect (timeout=1500):p bcast. Nakack (GC_LAG=50;RETRANSM
it_timeout=300,600,1200,2400,4800):p Bcast. STABLE (desired_avg_gossip=20000):
UNICAST (timeout=5000): FRAG (Frag_size=8096;down_thread=false;up_thread=fal
SE):p bcast. GMS (Join_timeout=5000;join_retry_timeout=2000;shun=false;print_loc
Al_addr=true)
#cache. cluster.multicast.ip=231.12.21.132
Once configured, this file is placed in Classpath and Oscache automatically locates the file when it is initialized and creates a cache instance based on its configuration.

Caching mechanism of Ibatis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.