You are viewing a plain text version of this content. The canonical link for it is here.
Posted to slide-dev@jakarta.apache.org by oz...@apache.org on 2003/11/14 13:52:52 UTC
cvs commit: jakarta-slide/lib commons-collections.jar
ozeigermann 2003/11/14 04:52:52
Modified: . build.xml
Added: src/share/org/apache/slide/util/locking MultiLevelLock.java
LockManager.java
src/share/org/apache/slide/util/locking/impl
GenericLockManager.java GenericLock.java
src/share/org/apache/slide/util
ByteSizeLimitedObjectCache.java XidWrapper.java
TxLRUObjectCache.java
src/share/org/apache/slide/store ExtendedStore.java
lib commons-collections.jar
Log:
Initial version of a revised kernel store (ExtendedStore) supporting transactional caching and a bunch of helper classes
Revision Changes Path
1.1 jakarta-slide/src/share/org/apache/slide/util/locking/MultiLevelLock.java
Index: MultiLevelLock.java
===================================================================
package org.apache.slide.util.locking;
/**
*
* A multi level lock. Depending on the implementation more than one owner may own a certain lock level on the same lock.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
* @see LockManager
*/
public interface MultiLevelLock {
/**
* Tries to acquire a certain lock level on this lock.
*
* @param ownerId a unique id identifying the entity that wants to acquire a certain lock level on this lock
* @param targetLockLevel the lock level to acquire
* @param wait <code>true</code> if this method shall block when the desired lock level can not be acquired
* @param reentrant <code>true</code> if lock levels of the same entity acquired earlier
* should not restrict compatibility with the lock level desired now
* @param timeoutMSecs if blocking is enabled by the <code>wait</code> parameter this specifies the maximum wait time in milliseconds
* @return <code>true</code> if the lock actually was acquired
* @throws InterruptedException when the thread waiting on this method is interrupted
*/
public boolean acquire(Object ownerId, int targetLockLevel, boolean wait, boolean reentrant, long timeoutMSecs)
throws InterruptedException;
/**
* Releases any lock levels the specified owner may hold on this lock.
*
* @param ownerId a unique id identifying the entity that wants to release all lock levels
*/
public void release(Object ownerId);
/**
* Retuns the highest lock level the specified owner holds on this lock or <code>0</code> if it holds no locks at all.
*
* @param ownerId a unique id identifying the entity that wants to release all lock levels
* @return the highest lock level
*/
public int getLockLevel(Object ownerId);
}
1.1 jakarta-slide/src/share/org/apache/slide/util/locking/LockManager.java
Index: LockManager.java
===================================================================
package org.apache.slide.util.locking;
/**
*
* A manager for multi level locks on resources. Encapsulates creation, removal, and retrieval of locks.
* Each resource can have at most a single lock. However, it may be possible for more than one
* accessing entity to have influence on this lock via different lock levels that may be
* provided by the according implementation of {@link MultiLevelLock}.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
* @see MultiLevelLock
*/
public interface LockManager {
/**
* Either gets an existing lock on the specified resource or creates one if none exists.
* This methods guarantees to do this atomically.
*
* @param resourceId the resource to get or create the lock on
* @return the lock for the specified resource
*/
public MultiLevelLock atomicGetOrCreateLock(Object resourceId);
/**
* Gets an existing lock on the specified resource. If none exists it returns <code>null</code>.
*
* @param resourceId the resource to get the lock for
* @return the lock on the specified resource
*/
public MultiLevelLock getLock(Object resourceId);
/**
* Removes the specified lock from the associated resource.
*
* @param lock the lock to be removed
*/
public void removeLock(MultiLevelLock lock);
}
1.1 jakarta-slide/src/share/org/apache/slide/util/locking/impl/GenericLockManager.java
Index: GenericLockManager.java
===================================================================
package org.apache.slide.util.locking.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.slide.store.txfile.StoreLogger;
import org.apache.slide.util.locking.LockManager;
import org.apache.slide.util.locking.MultiLevelLock;
/**
* Manager for {@link GenericLock}s on resources.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
*/
public class GenericLockManager implements LockManager {
protected Map globalLocks = new HashMap();
protected int maxLockLevel = -1;
protected StoreLogger logger;
public GenericLockManager(int maxLockLevel, StoreLogger logger) throws IllegalArgumentException {
if (maxLockLevel < 1)
throw new IllegalArgumentException(
"The maximum lock level must be at least 1 (" + maxLockLevel + " was specified)");
this.maxLockLevel = maxLockLevel;
this.logger = logger.cloneWithNewLogChannel("Locking");
}
public MultiLevelLock getLock(Object resourceId) {
synchronized (globalLocks) {
return (MultiLevelLock) globalLocks.get(resourceId);
}
}
public MultiLevelLock atomicGetOrCreateLock(Object resourceId) {
synchronized (globalLocks) {
MultiLevelLock lock = getLock(resourceId);
if (lock == null) {
lock = createLock(resourceId);
globalLocks.put(resourceId, lock);
}
return lock;
}
}
public void removeLock(MultiLevelLock lock) {
synchronized (globalLocks) {
globalLocks.remove(lock);
}
}
/**
* Gets all locks as orignials, <em>no copies</em>.
*
* @return collection holding all locks.
*/
public Collection getLocks() {
synchronized (globalLocks) {
return globalLocks.values();
}
}
protected GenericLock createLock(Object resourceId) {
synchronized (globalLocks) {
GenericLock lock = new GenericLock(resourceId, maxLockLevel, logger);
globalLocks.put(resourceId, lock);
return lock;
}
}
}
1.1 jakarta-slide/src/share/org/apache/slide/util/locking/impl/GenericLock.java
Index: GenericLock.java
===================================================================
package org.apache.slide.util.locking.impl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.slide.store.txfile.StoreLogger;
import org.apache.slide.util.locking.MultiLevelLock;
/**
*
* A generic implementaion of a simple multi level lock.
*
* <p>The idea is to have an ascending number of
* lock levels ranging from <code>0</code> to <code>maxLockLevel</code> as specified in
* {@link #GenericLock(Object, int)}: the higher the lock level the stronger and more restrictive the lock. To determine which lock may coexist with other locks you have to imagine matching pairs of lock levels.
* For each pair both parts allow for all lock levels less than or equal to the matching other part. Pairs are composed by the lowest and highest level not yet part of a pair and successively applying this
* method until no lock level is left. For an even amount of levels each level is part of exactly one pair.
* For an odd amount the middle level is paired with itself. The highst lock level may coexist with the lowest one (<code>0</code>) which by definition means
* <code>NO LOCK</code>. This implies that you will have to specify at least one other lock level and thus
* set <code>maxLockLevel</code> to at least <code>1</code>.</p>
*
* <p>Although this may sound complicated, in practice this is quite simple. Let us imagine you have three lock levels:
* <ul>
* <li><code>0</code>: <code>NO LOCK</code> (always needed by the
* implementation of this lock)
* <li><code>1</code>: <code>SHARED</code>
* <li><code>2</code>: <code>EXCLUSIVE</code>
* </ul>
* Accordingly, you will have to set <code>maxLockLevel</code> to <code>2</code>.
* Now, there are two pairs of levels
* <ul>
* <li><code>NO LOCK</code> with <code>EXCLUSIVE</code>
* <li><code>SHARED</code> with <code>SHARED</code>
* </ul>
* This means when the current highest lock level is
* <code>NO LOCK</code> everything less or equal to
* <code>EXCLUSIVE</code> is allowed - which means every other lock
* level. On the other side <code>EXCLUSIVE</code> allows exacly for
* <code>NO LOCK</code> - which means nothing else. In conclusion,
* <code>SHARED</code> allows for <code>SHARED</code> or <code>NO
* LOCK</code>, but not for <code>EXCLUSIVE</code>. To make this very
* clear have a look at this table, where <code>o</code> means
* compatible or can coexist and <code>x</code> means incompatible or can
* not coexist:</p>
* <table>
* <tbody>
* <tr>
* <td align="center"></td>
* <td align="center">NO LOCK</td>
* <td align="center">SHARED</td><td align="center">EXCLUSIVE</td>
* </tr>
* <tr><td align="center">NO LOCK</td><td align="center">o</td><td align="center">o</td><td align="center">o</td>
* </tr>
* <tr><td align="center">SHARED</td><td align="center">o</td><td align="center">o</td><td align="center">x</td>
* </tr>
* <tr><td align="center">EXCLUSIVE</td><td align="center" align="center">o</td><td align="center">x</td><td align="center">x</td>
* </tr>
* </tbody>
* </table>
*
* </p>
*
* General limitations include:<br>
* <ul>
* <li>You are restricted to the scheme described above
* <li>There are no preferences configurable for lock levels. This means whenever more than
* one party waits for a lock you can not specify which one is to be preferred. Under certain circumstances
* I might be nice to have the opportunity to give priority to parties either applying for
* higher or lower lock levels. It might even be desirable not only to give priority to higher or lower locks,
* but to a special level. For example you do not want to prefer higher lock levels, but exactly lock
* level <code>3</code> which might stand for <code>WRITE</code> access.
* <li>It is not possible to represent hierarchical locks, i.e. locks having descendants
* that are locked whenever the lock itself is locked. Consequently, there also is no notion
* of an intention lock.
* <li>You can not specify a timeframe for the validity of a lock. This means an owner of a thread
* can never lose a lock except when <em>actively</em> releasing it. This is bad when an owner either
* forgets to release a lock or is not able to do so due to error states or abnormal termination.
* </ul>
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
*/
public class GenericLock implements MultiLevelLock {
private Object resourceId;
private Map owners = new HashMap();
private int maxLockLevel;
protected StoreLogger logger;
/**
* Creates a new lock.
*
* @param resourceId identifier for the resource associated to this lock
* @param maxLockLevel highest allowed lock level as described in class intro
*/
public GenericLock(Object resourceId, int maxLockLevel, StoreLogger logger) {
if (maxLockLevel < 1)
throw new IllegalArgumentException(
"The maximum lock level must be at least 1 (" + maxLockLevel + " was specified)");
this.resourceId = resourceId;
this.maxLockLevel = maxLockLevel;
this.logger = logger;
}
public synchronized boolean acquire(
Object ownerId,
int targetLockLevel,
boolean wait,
boolean reentrant,
long timeoutMSecs)
throws InterruptedException {
logger.logFiner(
ownerId.toString()
+ " trying to acquire lock for "
+ resourceId.toString()
+ " at level "
+ targetLockLevel
+ " at "
+ System.currentTimeMillis());
if (tryLock(ownerId, targetLockLevel, reentrant)) {
logger.logFiner(
ownerId.toString()
+ " actually acquired lock for "
+ resourceId.toString()
+ " at "
+ System.currentTimeMillis());
return true;
} else {
if (!wait) {
return false;
} else {
long tryEndMSecs = System.currentTimeMillis() + timeoutMSecs;
while (System.currentTimeMillis() < tryEndMSecs) {
logger.logFiner(
ownerId.toString()
+ " waiting on "
+ resourceId.toString()
+ " for msecs "
+ timeoutMSecs
+ " at "
+ System.currentTimeMillis());
wait(timeoutMSecs);
if (tryLock(ownerId, targetLockLevel, reentrant)) {
logger.logFiner(
ownerId.toString()
+ " waiting on "
+ resourceId.toString()
+ " eventually got the lock at "
+ System.currentTimeMillis());
return true;
}
}
return false;
}
}
}
public synchronized void release(Object ownerId) {
if (owners.remove(ownerId) != null) {
logger.logFiner(
ownerId.toString()
+ " releasing lock for "
+ resourceId.toString()
+ " at "
+ System.currentTimeMillis());
notifyAll();
}
}
public synchronized int getLockLevel(Object ownerId) {
LockOwner owner = (LockOwner) owners.get(ownerId);
if (owner == null) {
return 0;
} else {
return owner.lockLevel;
}
}
/**
* Gets the resource assotiated to this lock.
*
* @return identifier for the resource associated to this lock
*/
public Object getResourceId() {
return resourceId;
}
/**
* Gets the lowest lock level possible.
*
* @return minimum lock level
*/
public int getLevelMinLock() {
return 0;
}
/**
* Gets the highst lock level possible.
*
* @return maximum lock level
*/
public int getLevelMaxLock() {
return maxLockLevel;
}
protected synchronized LockOwner getMaxLevelOwner() {
return getMaxLevelOwnerNotMe(null);
}
protected synchronized LockOwner getMaxLevelOwnerNotMe(LockOwner me) {
LockOwner maxOwner = null;
for (Iterator it = owners.values().iterator(); it.hasNext();) {
LockOwner owner = (LockOwner) it.next();
if (!owner.equals(me) && (maxOwner == null || maxOwner.lockLevel < owner.lockLevel)) {
maxOwner = owner;
}
}
return maxOwner;
}
protected synchronized void setLockLevel(Object ownerId, LockOwner lock, int targetLockLevel) {
// be sure there exists at most one lock per owner
if (lock != null) {
logger.logFinest(
ownerId.toString()
+ " upgrading lock for "
+ resourceId.toString()
+ " to level "
+ targetLockLevel
+ " at "
+ System.currentTimeMillis());
lock.lockLevel = targetLockLevel;
} else {
logger.logFinest(
ownerId.toString()
+ " getting new lock for "
+ resourceId.toString()
+ " at level "
+ targetLockLevel
+ " at "
+ System.currentTimeMillis());
owners.put(ownerId, new LockOwner(ownerId, targetLockLevel));
}
}
protected synchronized boolean tryLock(Object ownerId, int targetLockLevel, boolean reentrant) {
LockOwner myLock = (LockOwner) owners.get(ownerId);
// determine highest owner
LockOwner highestOwner;
if (myLock != null && reentrant) {
if (targetLockLevel <= myLock.lockLevel) {
// we already have it
return true;
} else {
// our own lock will not be compromised by ourself's
highestOwner = getMaxLevelOwnerNotMe(myLock);
}
} else {
highestOwner = getMaxLevelOwner();
}
// what is our current lock level?
int currentLockLevel;
if (highestOwner != null) {
currentLockLevel = highestOwner.lockLevel;
} else {
currentLockLevel = getLevelMinLock();
}
// we are only allowed to acquire our locks if we do not compromise locks of any other lock owner
if (targetLockLevel <= getLevelMaxLock() - currentLockLevel) {
setLockLevel(ownerId, myLock, targetLockLevel);
return true;
} else {
return false;
}
}
private static class LockOwner {
public Object ownerId;
public int lockLevel;
public LockOwner(Object ownerId, int lockLevel) {
this.ownerId = ownerId;
this.lockLevel = lockLevel;
}
}
}
1.1 jakarta-slide/src/share/org/apache/slide/util/ByteSizeLimitedObjectCache.java
Index: ByteSizeLimitedObjectCache.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/share/org/apache/slide/util/ByteSizeLimitedObjectCache.java,v 1.1 2003/11/14 12:52:51 ozeigermann Exp $
* $Revision: 1.1 $
* $Date: 2003/11/14 12:52:51 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Slide", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.slide.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import org.apache.slide.util.logger.Logger;
import org.apache.commons.collections.LRUMap;
/**
* Transactional LRU byte counting object cache. Caches objects using a least-recently-used strategy.
* Asserts a given overall size of all cached objects does not exceed a specified limit.
*
* It provides basic isolation from other transactions and atomicity of all operations. As
* no locking is used (which is undesirable mainly as a cache should never block and a commit must never fail)
* serializability needs to be guaranteed by underlying stores.
*
* <em>Note</em>: Unlike {@link TxLRUObjectCache} this cache also limits the size of temporary caches inside transactions.
* This is necessary as size of bytes in a transaction can become really big. In case an entry can not be cached inisde a
* transaction it will be marked as invalid after commit of that tx.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
* @version $Revision: 1.1 $
* @see TxLRUObjectCache
*/
public class ByteSizeLimitedObjectCache extends TxLRUObjectCache {
// amount of entries that are at most removed from cache to make room for a new entry
protected static final int MAX_FREEING_TRIES = 10;
protected long globalByteSize;
protected int txCacheSize;
protected long txByteSize;
protected long maxByteSizePerEntry;
/**
* Creates a new object cache. The maximum cache size can be configured for local transaction
* caches as well as on a global level.
*
* The idea of having a maximum size in bytes per entry is to prevent a large entry
* to displace many small entries.
*
* @param globalCacheSize maximum size in objects of global cache
* @param txCacheSize maximum size in objects for local transaction cache
* @param globalByteSize maximum size in bytes of global cache
* @param txByteSize maximum size in bytes for local transaction cache
* @param maxByteSizePerEntry maximum size of a single cache entry in bytes
* @param name the name used to construct logging category / channel
* @param logger Slide logger to be used for logging
*/
public ByteSizeLimitedObjectCache(
int globalCacheSize,
int txCacheSize,
long globalByteSize,
long txByteSize,
long maxByteSizePerEntry,
String name,
Logger logger) {
super(globalCacheSize, name, logger);
globalCache = new SizeCountingLRUMap(globalCacheSize, globalByteSize, maxByteSizePerEntry);
this.globalByteSize = globalByteSize;
this.txCacheSize = txCacheSize;
this.txByteSize = txByteSize;
this.maxByteSizePerEntry = maxByteSizePerEntry;
logChannel = "ByteSizeLimitedObjectCache";
if (name != null) {
logChannel += "." + name;
}
}
public synchronized void clear() {
super.clear();
}
public synchronized boolean canCache(Object txId, long byteSize) {
long maxSize;
if (txId != null) {
maxSize = globalByteSize;
} else {
maxSize = txByteSize;
}
return (maxSize >= byteSize && maxByteSizePerEntry >= byteSize);
}
public synchronized void put(Object txId, Object key, Object value, long byteSize) {
if (key == null) {
logger.log(txId + " adding null key with byte size " + byteSize, logChannel, Logger.WARNING);
}
if (txId != null) {
// if it has been deleted before, undo this
Set deleteCache = (Set) txDeleteCaches.get(txId);
deleteCache.remove(key);
SizeCountingLRUMap changeCache = (SizeCountingLRUMap) txChangeCaches.get(txId);
changeCache.put(key, value, byteSize);
if (loggingEnabled) {
logger.log(txId + " added '" + key + "' with byte size " + byteSize, logChannel, Logger.DEBUG);
}
} else {
((SizeCountingLRUMap) globalCache).put(key, value, byteSize);
if (loggingEnabled) {
logger.log("Added '" + key + "' with byte size " + byteSize, logChannel, Logger.DEBUG);
}
}
}
public synchronized void start(Object txId) {
if (txId != null) {
txChangeCaches.put(txId, new SizeCountingLRUMap(txCacheSize, txByteSize, maxByteSizePerEntry, txId));
txDeleteCaches.put(txId, new HashSet());
}
}
public synchronized void commit(Object txId) {
if (txId != null) {
// apply local changes and deletes (is atomic as we have a global lock on this TxCache)
SizeCountingLRUMap changeCache = (SizeCountingLRUMap) txChangeCaches.get(txId);
for (Iterator it = changeCache.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
long byteSize = changeCache.getByteSize(entry.getKey());
if (byteSize == -1L) {
globalCache.put(entry.getKey(), entry.getValue());
} else {
((SizeCountingLRUMap) globalCache).put(entry.getKey(), entry.getValue(), byteSize);
}
}
Set deleteCache = (Set) txDeleteCaches.get(txId);
for (Iterator it = deleteCache.iterator(); it.hasNext();) {
Object key = it.next();
globalCache.remove(key);
}
if (loggingEnabled) {
logger.log(
txId
+ " committed "
+ changeCache.size()
+ " changes and "
+ deleteCache.size()
+ " scheduled deletes",
logChannel,
Logger.DEBUG);
}
// finally forget about tx
forget(txId);
}
}
protected class SizeCountingLRUMap extends LRUMap {
private Map shadowSizes;
private long globalSize;
private long maxByteSize;
private long maxByteSizePerEntry;
private Object txId;
public SizeCountingLRUMap(int size, long maxByteSize, long maxByteSizePerEntry, Object txId) {
this(size, maxByteSize, maxByteSizePerEntry);
this.txId = txId;
}
public SizeCountingLRUMap(int size, long maxByteSize, long maxByteSizePerEntry) {
super(size);
this.shadowSizes = new HashMap();
this.globalSize = 0;
this.maxByteSize = maxByteSize;
this.maxByteSizePerEntry = maxByteSizePerEntry;
}
public Object put(Object key, Object value, long byteSize) {
// is it too big to be cached?
if (byteSize > maxByteSizePerEntry || byteSize > maxByteSize) {
if (loggingEnabled) {
logger.log(txId + " for '" + key + "' is too big to be cached", logChannel, Logger.DEBUG);
}
Object oldValue = get(key);
// invalidate previous entry if present
// XXX this relies on an implementation detail in TxLRUByteCache.put
// removal from delete cache must be done before trying to add to
// change cache using this method; if not our undoing will be partly
// undone (again) in TxLRUObjectCache.put
invalidate(key);
return oldValue;
} else {
// be sure to return allocated bytes before readding
freeBytes(key);
// ok, we decided to cache this entry, make room for it
for (int i = 0; globalSize + byteSize > maxByteSize && i < MAX_FREEING_TRIES; i++)
if (loggingEnabled) {
logger.log(
txId
+ " for '"
+ key
+ "' needs "
+ Long.toString(globalSize + byteSize - maxByteSize)
+ " bytes more to be cached. Freeing bytes!",
logChannel,
Logger.DEBUG);
}
// this will call back processRemovedLRU and will thus free bytes
removeLRU();
}
// was this successful?
if (globalSize + byteSize > maxByteSize) {
shadowSizes.put(key, new Long(byteSize));
globalSize += byteSize;
return super.put(key, value);
} else {
Object oldValue = get(key);
invalidate(key);
return oldValue;
}
}
public long getByteSize(Object key) {
Long lSize = (Long) shadowSizes.get(key);
if (lSize != null) {
return lSize.longValue();
} else {
return -1L;
}
}
protected void freeBytes(Object key) {
Long lSize = (Long) shadowSizes.remove(key);
if (lSize != null) {
long size = lSize.longValue();
globalSize -= size;
}
}
protected void invalidate(Object key) {
// if it is no longer cached, it still means entry currently
// in global map gets invalid upon commit of this tx
freeBytes(key);
ByteSizeLimitedObjectCache.this.remove(txId, key);
if (loggingEnabled) {
logger.log(txId + " invalidated '" + key + "'", logChannel, Logger.DEBUG);
}
}
// notify cache that this entry has been removed by LRU strategy (called back by LRUMap)
protected void processRemovedLRU(Object key, Object value) {
invalidate(key);
}
}
}
1.1 jakarta-slide/src/share/org/apache/slide/util/XidWrapper.java
Index: XidWrapper.java
===================================================================
package org.apache.slide.util;
import javax.transaction.xa.Xid;
import java.lang.Object;
//import java.util.Arrays;
import java.lang.String;
/**
* Wraps an <code>Xid</code> to guarantee methods for equality and hashcode are
* implemented correctly. This is escpecially necessary when the <code>Xid</code> is used as a key in a <code>HashMap</code>.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
*
*/
public class XidWrapper implements Xid {
private static boolean includeBranch = true;
// for slide branch qualifier must not be included
public static final void setIncludeBranch(boolean includeBranch) {
XidWrapper.includeBranch = includeBranch;
}
public static final Xid wrap(Xid xid) {
return (xid instanceof XidWrapper ? xid : new XidWrapper(xid));
}
private final Xid xid;
private final String asString;
private final int hashCode;
public XidWrapper(Xid xid) {
this.xid = xid;
// do calculations once for performance
asString =
new String(xid.getGlobalTransactionId())
+ (includeBranch ? "-" + new String(xid.getBranchQualifier()) : "");
hashCode = asString.hashCode();
}
public Xid getXid() {
return xid;
}
public int getFormatId() {
return xid.getFormatId();
}
public byte[] getGlobalTransactionId() {
return xid.getGlobalTransactionId();
}
public byte[] getBranchQualifier() {
return xid.getBranchQualifier();
}
public boolean equals(Object o) {
return (o != null && asString.equals(o.toString()));
/*
if (this == o) {
return true;
}
if (o != null && o instanceof Xid) {
Xid xid2 = (Xid) o;
// we do not need equality of format Id
return (
Arrays.equals(xid.getGlobalTransactionId(), xid2.getGlobalTransactionId())
&& Arrays.equals(xid.getBranchQualifier(), xid2.getBranchQualifier()));
}
return false;
*/
}
public String toString() {
return asString;
}
public int hashCode() {
return hashCode;
}
}
1.1 jakarta-slide/src/share/org/apache/slide/util/TxLRUObjectCache.java
Index: TxLRUObjectCache.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/share/org/apache/slide/util/TxLRUObjectCache.java,v 1.1 2003/11/14 12:52:51 ozeigermann Exp $
* $Revision: 1.1 $
* $Date: 2003/11/14 12:52:51 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Slide", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.slide.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.slide.util.logger.Logger;
import org.apache.commons.collections.LRUMap;
/**
* Transactional LRU object cache. Caches objects using a least-recently-used strategy.
*
* It provides basic isolation from other transactions and atomicity of all operations. As
* no locking is used (which is undesirable mainly as a cache should never block and a commit must never fail)
* serializability needs to be guaranteed by underlying stores.
* <br>
* <br>
* <em>Caution</em>: Only global caches are limited by given size.
* Size of temporary data inside a transaction is unlimited.
* <br>
* <br>
* <em>Note</em>: This cache has no idea if the data it caches in transactions are read from or written to store.
* It thus handles both access types the same way. This means read accesses are cached in transactions even though they
* could be cached globally. Like write accesses they will be moved to global cache at commit time.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
* @version $Revision: 1.1 $
*/
public class TxLRUObjectCache {
protected Map globalCache;
protected Map txChangeCaches;
protected Map txDeleteCaches;
protected int hits = 0;
protected int misses = 0;
protected String name;
protected Logger logger;
protected String logChannel;
protected final boolean loggingEnabled;
/**
* Creates a new object cache.
*
* @param globalCacheSize maximum size in objects of global cache
* @param name the name used to construct logging category / channel
* @param logger Slide logger to be used for logging
*/
public TxLRUObjectCache(int globalCacheSize, String name, Logger logger) {
globalCache = new LRUMap(globalCacheSize);
txChangeCaches = new HashMap();
txDeleteCaches = new HashMap();
this.name = name;
this.logger = logger;
logChannel = "TxLRUObjectCache";
if (name != null) {
logChannel += "." + name;
}
// used for guarded logging as preparation is expensive
loggingEnabled = logger.isEnabled(logChannel, Logger.DEBUG);
}
public TxLRUObjectCache(int globalCacheSize) {
this(globalCacheSize, null, null);
}
public synchronized void clear() {
globalCache.clear();
txChangeCaches.clear();
txDeleteCaches.clear();
}
public synchronized Object get(Object txId, Object key) {
if (txId != null) {
Set deleteCache = (Set) txDeleteCaches.get(txId);
if (deleteCache.contains(key)) {
hit(txId, key);
// reflects that entry has been deleted in this tx
return null;
}
Map changeCache = (Map) txChangeCaches.get(txId);
Object changed = changeCache.get(key);
if (changed != null) {
hit(txId, key);
// if object has been changed in this tx, get the local one
return changed;
}
}
// as fall back return value from global cache (if present)
Object global = globalCache.get(key);
if (global != null) {
hit(txId, key);
} else {
miss(txId, key);
}
return global;
}
public synchronized void put(Object txId, Object key, Object value) {
if (txId != null) {
// if it has been deleted before, undo this
Set deleteCache = (Set) txDeleteCaches.get(txId);
deleteCache.remove(key);
Map changeCache = (Map) txChangeCaches.get(txId);
changeCache.put(key, value);
if (loggingEnabled) {
logger.log(txId + " added '" + key + "'", logChannel, Logger.DEBUG);
}
} else {
globalCache.put(key, value);
if (loggingEnabled) {
logger.log("Added '" + key + "'", logChannel, Logger.DEBUG);
}
}
}
public synchronized void remove(Object txId, Object key) {
if (txId != null) {
// if it has been changed before, undo this
Map changeCache = (Map) txChangeCaches.get(txId);
changeCache.remove(key);
Set deleteCache = (Set) txDeleteCaches.get(txId);
deleteCache.add(key);
// guard logging as preparation is expensive
if (loggingEnabled) {
logger.log(txId + " removed '" + key + "'", logChannel, Logger.DEBUG);
}
} else {
globalCache.remove(key);
if (loggingEnabled) {
logger.log("Removed '" + key + "'", logChannel, Logger.DEBUG);
}
}
}
public synchronized void start(Object txId) {
if (txId != null) {
txChangeCaches.put(txId, new HashMap());
txDeleteCaches.put(txId, new HashSet());
}
}
public synchronized void rollback(Object txId) {
if (txId != null) {
if (loggingEnabled) {
Map changeCache = (Map) txChangeCaches.get(txId);
Set deleteCache = (Set) txDeleteCaches.get(txId);
logger.log(
txId
+ " rolled back "
+ changeCache.size()
+ " changes and "
+ deleteCache.size()
+ " scheduled deletes",
logChannel,
Logger.DEBUG);
}
// simply forget about tx
forget(txId);
}
}
public synchronized void commit(Object txId) {
if (txId != null) {
// apply local changes and deletes (is atomic as we have a global lock on this TxCache)
Map changeCache = (Map) txChangeCaches.get(txId);
for (Iterator it = changeCache.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
globalCache.put(entry.getKey(), entry.getValue());
}
Set deleteCache = (Set) txDeleteCaches.get(txId);
for (Iterator it = deleteCache.iterator(); it.hasNext();) {
Object key = it.next();
globalCache.remove(key);
}
if (loggingEnabled) {
logger.log(
txId
+ " committed "
+ changeCache.size()
+ " changes and "
+ deleteCache.size()
+ " scheduled deletes",
logChannel,
Logger.DEBUG);
}
// finally forget about tx
forget(txId);
}
}
public synchronized void forget(Object txId) {
if (txId != null) {
txChangeCaches.remove(txId);
txDeleteCaches.remove(txId);
}
}
protected void hit(Object txId, Object key) {
hits++;
log(txId, key, true);
}
protected void miss(Object txId, Object key) {
misses++;
log(txId, key, false);
}
protected void log(Object txId, Object key, boolean hit) {
if (loggingEnabled) {
StringBuffer log = new StringBuffer();
if (txId != null) {
Map changeCache = (Map) txChangeCaches.get(txId);
Set deleteCache = (Set) txDeleteCaches.get(txId);
log.append(txId + " (" + changeCache.size() + ", " + deleteCache.size() + ") ");
}
log.append(
(hit ? "Cache Hit: '" : "Cache Miss: '")
+ key
+ "' "
+ hits
+ " / "
+ misses
+ " / "
+ globalCache.size());
logger.log(log.toString(), logChannel, Logger.DEBUG);
}
}
}
1.182 +3 -0 jakarta-slide/build.xml
Index: build.xml
===================================================================
RCS file: /home/cvs/jakarta-slide/build.xml,v
retrieving revision 1.181
retrieving revision 1.182
diff -u -r1.181 -r1.182
--- build.xml 28 Jul 2003 15:46:05 -0000 1.181
+++ build.xml 14 Nov 2003 12:52:52 -0000 1.182
@@ -70,6 +70,7 @@
<property name="taglibs-standard.jar" value="${taglibs-standard.lib}/standard.jar"/>
<property name="commons-httpclient.jar" value="lib/commons-httpclient.jar"/>
<property name="commons-logging.jar" value="lib/commons-logging.jar"/>
+ <property name="commons-collections.jar" value="lib/commons-collections.jar"/>
<!-- =================================================================== -->
<!-- Build Properties -->
<!-- =================================================================== -->
@@ -118,6 +119,7 @@
<pathelement location="${jta.jar}"/>
<pathelement location="${jdom.jar}"/>
<pathelement location="${jmx.jar}"/>
+ <pathelement location="${commons-collections.jar}"/>
</path>
<path id="manager.classpath">
<pathelement location="${xmlapi.jar}"/>
@@ -137,6 +139,7 @@
<pathelement location="${slide.build}/classes"/>
<pathelement location="${commons-dbcp.jar}"/>
<pathelement location="${commons-pool.jar}"/>
+ <pathelement location="${commons-collections.jar}"/>
</path>
<path id="wrappers.classpath">
<pathelement location="${jta.jar}"/>
1.1 jakarta-slide/src/share/org/apache/slide/store/ExtendedStore.java
Index: ExtendedStore.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/share/org/apache/slide/store/ExtendedStore.java,v 1.1 2003/11/14 12:52:52 ozeigermann Exp $
* $Revision: 1.1 $
* $Date: 2003/11/14 12:52:52 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Slide", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.slide.store;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.ServiceParameterErrorException;
import org.apache.slide.common.ServiceParameterMissingException;
import org.apache.slide.common.Uri;
import org.apache.slide.content.NodeRevisionContent;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.NodeRevisionDescriptors;
import org.apache.slide.content.NodeRevisionNumber;
import org.apache.slide.content.RevisionAlreadyExistException;
import org.apache.slide.content.RevisionDescriptorNotFoundException;
import org.apache.slide.content.RevisionNotFoundException;
import org.apache.slide.lock.LockTokenNotFoundException;
import org.apache.slide.lock.NodeLock;
import org.apache.slide.security.NodePermission;
import org.apache.slide.structure.ObjectAlreadyExistsException;
import org.apache.slide.structure.ObjectNode;
import org.apache.slide.structure.ObjectNotFoundException;
import org.apache.slide.util.*;
import org.apache.slide.util.ObjectCache;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import org.apache.slide.util.logger.Logger;
/**
* Store that allows for transactional caching of data. Takes over much modified code from StandardStore.
* That's why Remy is listed as author as well.
*
* @author <a href="mailto:ozeigermann@c1-fse.de">Oliver Zeigermann</a>
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
* @version $Revision: 1.1 $
*/
public class ExtendedStore extends AbstractStore {
private static final String LOG_CHANNEL = ExtendedStore.class.getName();
// just for debugging
private static final boolean globalCacheOff = false;
protected static final int DEFAULT_OBJECT_GLOBAL_CACHE_SIZE = 10000;
protected static final String GLOBAL_OBJECT_CACHE_SIZE_PARAMETER = "object-cache-size";
protected static final int DEFAULT_GLOBAL_PERMISSION_CACHE_SIZE = 10000;
protected static final String GLOBAL_PERMISSION_CACHE_SIZE_PARAMETER = "permission-cache-size";
protected static final int DEFAULT_GLOBAL_LOCK_CACHE_SIZE = 100;
protected static final String GLOBAL_LOCK_CACHE_SIZE_PARAMETER = "lock-cache-size";
protected static final int DEFAULT_GLOBAL_DESCRIPTORS_CACHE_SIZE = 10000;
protected static final String GLOBAL_DESCRIPTORS_CACHE_SIZE_PARAMETER = "descriptors-cache-size";
protected static final int DEFAULT_GLOBAL_DESCRIPTOR_CACHE_SIZE = 10000;
protected static final String GLOBAL_DESCRIPTOR_CACHE_SIZE_PARAMETER = "descriptor-cache-size";
protected static final int DEFAULT_GLOBAL_CONTENT_CACHE_SIZE = 10000;
protected static final String GLOBAL_CONTENT_CACHE_SIZE_PARAMETER = "content-cache-size";
protected static final boolean DEFAULT_ENABLE_CONTENT_CACHING = false;
protected static final String ENABLE_CONTENT_CACHING_PARAMETER = "enable-content-caching";
protected static final int DEFAULT_TX_CONTENT_CACHE_SIZE = 1000;
protected static final String TX_CONTENT_CACHE_SIZE_PARAMETER = "tx-content-cache-size";
protected static final long DEFAULT_CONTENT_CACHE_BYTES = 10000000; // 10 M
protected static final String CONTENT_CACHE_BYTES_PARAMETER = "content-cache-bytes";
protected static final long DEFAULT_TX_CONTENT_CACHE_BYTES = 1000000; // 1 M
protected static final String TX_CONTENT_CACHE_BYTES_PARAMETER = "tx-content-cache-bytes";
protected static final long DEFAULT_MAX_CONTENT_BYTES_PER_ENTRY = 50000; // 50 K
protected static final String MAX_CONTENT_BYTES_PER_ENTRY_PARAMETER = "max-content-bytes-per-entry";
// there might be at least one active transaction branch per thread
protected ThreadLocal activeTransactionBranch = new ThreadLocal();
protected TxContentCacheWrapper contentCache;
protected TxCacheWrapper objectsCache;
protected TxCacheWrapper permissionsCache;
protected TxCacheWrapper locksCache;
protected TxCacheWrapper descriptorsCache;
protected TxCacheWrapper descriptorCache;
public void setParameters(Hashtable parameters)
throws ServiceParameterErrorException, ServiceParameterMissingException {
super.setParameters(parameters);
int globalObjectCacheSize = DEFAULT_OBJECT_GLOBAL_CACHE_SIZE;
int globalPermissionCacheSize = DEFAULT_GLOBAL_PERMISSION_CACHE_SIZE;
int globalLockCacheSize = DEFAULT_GLOBAL_LOCK_CACHE_SIZE;
int globalDescrtiptorsCacheSize = DEFAULT_GLOBAL_DESCRIPTORS_CACHE_SIZE;
int globalDescrtiptorCacheSize = DEFAULT_GLOBAL_DESCRIPTOR_CACHE_SIZE;
boolean contentCachingEnabled = DEFAULT_ENABLE_CONTENT_CACHING;
int globalContentCacheSize = DEFAULT_GLOBAL_CONTENT_CACHE_SIZE;
long contentCacheBytes = DEFAULT_CONTENT_CACHE_BYTES;
int txContentCacheSize = DEFAULT_TX_CONTENT_CACHE_SIZE;
long txContentCacheBytes = DEFAULT_TX_CONTENT_CACHE_BYTES;
long maxByteSizePerEntry = DEFAULT_MAX_CONTENT_BYTES_PER_ENTRY;
String globalObjectCacheSizeString = (String) parameters.get(GLOBAL_OBJECT_CACHE_SIZE_PARAMETER);
if (globalObjectCacheSizeString != null) {
try {
globalObjectCacheSize = Integer.parseInt(globalObjectCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting object cache size for store " + getName() + " to " + globalObjectCacheSize,
Logger.INFO);
String globalPermissionCacheSizeString = (String) parameters.get(GLOBAL_PERMISSION_CACHE_SIZE_PARAMETER);
if (globalPermissionCacheSizeString != null) {
try {
globalPermissionCacheSize = Integer.parseInt(globalPermissionCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting permission cache size for store " + getName() + " to " + globalPermissionCacheSize,
LOG_CHANNEL,
Logger.INFO);
String globalLockCacheSizeString = (String) parameters.get(GLOBAL_LOCK_CACHE_SIZE_PARAMETER);
if (globalLockCacheSizeString != null) {
try {
globalLockCacheSize = Integer.parseInt(globalLockCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting lock cache size for store " + getName() + " to " + globalLockCacheSize,
LOG_CHANNEL,
Logger.INFO);
String globalDescriptorsCacheSizeString = (String) parameters.get(GLOBAL_DESCRIPTORS_CACHE_SIZE_PARAMETER);
if (globalDescriptorsCacheSizeString != null) {
try {
globalDescrtiptorsCacheSize = Integer.parseInt(globalDescriptorsCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting descriptors cache size for store " + getName() + " to " + globalDescrtiptorsCacheSize,
LOG_CHANNEL,
Logger.INFO);
String globalDescriptorCacheSizeString = (String) parameters.get(GLOBAL_DESCRIPTOR_CACHE_SIZE_PARAMETER);
if (globalDescriptorCacheSizeString != null) {
try {
globalDescrtiptorCacheSize = Integer.parseInt(globalDescriptorCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting descriptor cache size for store " + getName() + " to " + globalDescrtiptorCacheSize,
LOG_CHANNEL,
Logger.INFO);
String enableContentCachingString = (String) parameters.get(ENABLE_CONTENT_CACHING_PARAMETER);
if (enableContentCachingString != null) {
contentCachingEnabled = Boolean.valueOf(enableContentCachingString).booleanValue();
}
getLogger().log(
"Setting content caching for store " + getName() + " to " + contentCachingEnabled,
LOG_CHANNEL,
Logger.INFO);
String globalContentCacheSizeString = (String) parameters.get(GLOBAL_CONTENT_CACHE_SIZE_PARAMETER);
if (globalContentCacheSizeString != null) {
try {
globalContentCacheSize = Integer.parseInt(globalContentCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log("Cache size must be an integer! Using default size", LOG_CHANNEL, Logger.WARNING);
}
}
getLogger().log(
"Setting content cache size for store " + getName() + " to " + globalContentCacheSize,
LOG_CHANNEL,
Logger.INFO);
String contentCacheBytesString = (String) parameters.get(CONTENT_CACHE_BYTES_PARAMETER);
if (contentCacheBytesString != null) {
try {
contentCacheBytes = Long.parseLong(contentCacheBytesString);
} catch (NumberFormatException nfe) {
getLogger().log(
"Content cache byte size must be an integer! Using default size",
LOG_CHANNEL,
Logger.WARNING);
}
}
getLogger().log(
"Setting content cache byte size for store " + getName() + " to " + contentCacheBytes,
LOG_CHANNEL,
Logger.INFO);
String txContentCacheSizeString = (String) parameters.get(TX_CONTENT_CACHE_SIZE_PARAMETER);
if (txContentCacheSizeString != null) {
try {
txContentCacheSize = Integer.parseInt(txContentCacheSizeString);
} catch (NumberFormatException nfe) {
getLogger().log(
"Content transaction cache size must be an integer! Using default size",
LOG_CHANNEL,
Logger.WARNING);
}
}
getLogger().log(
"Setting transaction content cache size for store " + getName() + " to " + txContentCacheSize,
LOG_CHANNEL,
Logger.INFO);
String txContentCacheBytesString = (String) parameters.get(TX_CONTENT_CACHE_BYTES_PARAMETER);
if (txContentCacheBytesString != null) {
try {
txContentCacheBytes = Long.parseLong(txContentCacheBytesString);
} catch (NumberFormatException nfe) {
getLogger().log(
"Transaction content cache byte size must be an integer! Using default size",
LOG_CHANNEL,
Logger.WARNING);
}
}
getLogger().log(
"Setting transaction content cache byte size for store " + getName() + " to " + txContentCacheBytes,
LOG_CHANNEL,
Logger.INFO);
String maxByteSizePerEntryString = (String) parameters.get(MAX_CONTENT_BYTES_PER_ENTRY_PARAMETER);
if (maxByteSizePerEntryString != null) {
try {
maxByteSizePerEntry = Long.parseLong(maxByteSizePerEntryString);
} catch (NumberFormatException nfe) {
getLogger().log(
"Maximum byte size for content cache entry must be an integer! Using default size",
LOG_CHANNEL,
Logger.WARNING);
}
}
getLogger().log(
"Setting maximum byte size for content cache entry for store " + getName() + " to " + maxByteSizePerEntry,
LOG_CHANNEL,
Logger.INFO);
init(
globalObjectCacheSize,
globalPermissionCacheSize,
globalLockCacheSize,
globalDescrtiptorsCacheSize,
globalDescrtiptorCacheSize,
contentCachingEnabled,
globalContentCacheSize,
contentCacheBytes,
txContentCacheSize,
txContentCacheBytes,
maxByteSizePerEntry);
}
//
// overloaded content methods with caching
//
public NodeRevisionContent retrieveRevisionContent(Uri uri, NodeRevisionDescriptor revisionDescriptor)
throws ServiceAccessException, RevisionNotFoundException {
if (contentStore.cacheResults() && contentCache != null) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
String key = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();
Object result = contentCache.get(key);
if (result != null) {
getLogger().log("Retrieving content at '" + key + "' from cache", LOG_CHANNEL, Logger.DEBUG);
// FIXME make a copy?! how?
return (NodeRevisionContent) result;
} else {
NodeRevisionContent revisionContent = super.retrieveRevisionContent(uri, revisionDescriptor);
long size = revisionDescriptor.getContentLength();
// Do not add content to global cache, as this might violate repeatable read.
// When we reread the entry later and another thread has committed its stuff
// into the global cache we might get a different version on the second read.
contentCache.put(key, revisionContent, size);
// contentCache.putForRead(key, revisionContent, size);
// FIXME make a copy?! how?
return revisionContent;
}
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.retrieveRevisionContent(uri, revisionDescriptor);
}
}
public void createRevisionContent(
Uri uri,
NodeRevisionDescriptor revisionDescriptor,
NodeRevisionContent revisionContent)
throws ServiceAccessException, RevisionAlreadyExistException {
long size = -1L;
if (contentStore.cacheResults() && contentCache != null) {
size = revisionDescriptor.getContentLength();
contentCache.precache(revisionContent, size);
}
super.createRevisionContent(uri, revisionDescriptor, revisionContent);
if (contentStore.cacheResults() && contentCache != null) {
enlist(this);
try {
String key = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();
contentCache.put(key, revisionContent, size);
} finally {
delist(this);
}
}
}
public void storeRevisionContent(
Uri uri,
NodeRevisionDescriptor revisionDescriptor,
NodeRevisionContent revisionContent)
throws ServiceAccessException, RevisionNotFoundException {
long size = -1L;
if (contentStore.cacheResults() && contentCache != null) {
size = revisionDescriptor.getContentLength();
contentCache.precache(revisionContent, size);
}
super.storeRevisionContent(uri, revisionDescriptor, revisionContent);
if (contentStore.cacheResults() && contentCache != null) {
enlist(this);
try {
String key = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();
contentCache.put(key, revisionContent, size);
} finally {
delist(this);
}
}
}
public void removeRevisionContent(Uri uri, NodeRevisionDescriptor revisionDescriptor)
throws ServiceAccessException {
if (contentStore.cacheResults() && contentCache != null) {
enlist(this);
try {
String key = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();
contentCache.remove(key);
} finally {
delist(this);
}
}
super.removeRevisionContent(uri, revisionDescriptor);
}
//
// overloaded retrieval methods guaranteeing cache enlistment in retrieval
//
public ObjectNode retrieveObject(Uri uri) throws ServiceAccessException, ObjectNotFoundException {
if (nodeStore.cacheResults()) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
Object tempObject = objectsCache.get(uri.toString());
if (tempObject != null) {
return ((ObjectNode) tempObject).cloneObject();
} else {
ObjectNode objectNode = super.retrieveObject(uri);
objectNode.validate(uri.toString());
objectsCache.put(uri.toString(), objectNode);
return objectNode.cloneObject();
}
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.retrieveObject(uri);
}
}
public void storeObject(Uri uri, ObjectNode object) throws ServiceAccessException, ObjectNotFoundException {
super.storeObject(uri, object);
if (nodeStore.cacheResults()) {
enlist(this);
try {
objectsCache.put(uri.toString(), object.cloneObject());
} finally {
delist(this);
}
}
}
public void createObject(Uri uri, ObjectNode object) throws ServiceAccessException, ObjectAlreadyExistsException {
super.createObject(uri, object);
if (nodeStore.cacheResults()) {
enlist(this);
try {
objectsCache.put(uri.toString(), object.cloneObject());
} finally {
delist(this);
}
}
}
public void removeObject(Uri uri, ObjectNode object) throws ServiceAccessException, ObjectNotFoundException {
super.removeObject(uri, object);
if (nodeStore.cacheResults()) {
enlist(this);
try {
objectsCache.remove(uri.toString());
} finally {
delist(this);
}
}
}
public void grantPermission(Uri uri, NodePermission permission) throws ServiceAccessException {
super.grantPermission(uri, permission);
if (securityStore.cacheResults()) {
enlist(this);
try {
NodePermission tempPermission = permission.cloneObject();
Object value = permissionsCache.get(uri.toString());
if (value == null) {
// populate the cache with the existing entries
enumeratePermissions(uri);
// and check if the cache contains a corresponding entry now
value = permissionsCache.get(uri.toString());
if (value == null) {
// no permissions for the Uri in the cache, so create a new
// entry
Vector permissionsVector = new Vector();
permissionsVector.addElement(tempPermission);
permissionsCache.put(uri.toString(), permissionsVector);
}
} else {
Vector permissionsVector = (Vector) value;
permissionsVector.addElement(tempPermission);
}
} finally {
delist(this);
}
}
}
public void revokePermission(Uri uri, NodePermission permission) throws ServiceAccessException {
super.revokePermission(uri, permission);
if (securityStore.cacheResults()) {
enlist(this);
try {
Object value = permissionsCache.get(uri.toString());
Vector permissionsVector = null;
if (value != null) {
permissionsVector = (Vector) value;
permissionsVector.removeElement(permission);
}
} finally {
delist(this);
}
}
}
public void revokePermissions(Uri uri) throws ServiceAccessException {
super.revokePermissions(uri);
if (securityStore.cacheResults()) {
enlist(this);
try {
Object value = permissionsCache.get(uri.toString());
Vector permissionsVector = null;
if (value != null) {
permissionsVector = (Vector) value;
permissionsVector.removeAllElements();
}
} finally {
delist(this);
}
}
}
public Enumeration enumeratePermissions(Uri uri) throws ServiceAccessException {
if (securityStore.cacheResults()) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
Object value = permissionsCache.get(uri.toString());
Vector permissionsVector = null;
if (value != null) {
permissionsVector = (Vector) value;
} else {
permissionsVector = new Vector();
Enumeration tempEnum = securityStore.enumeratePermissions(uri);
while (tempEnum.hasMoreElements()) {
NodePermission tempPermission = (NodePermission) tempEnum.nextElement();
tempPermission.validate(uri.toString());
permissionsVector.addElement(tempPermission);
}
permissionsCache.put(uri.toString(), permissionsVector);
}
return ((Vector) permissionsVector.clone()).elements();
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.enumeratePermissions(uri);
}
}
public void putLock(Uri uri, NodeLock lock) throws ServiceAccessException {
super.putLock(uri, lock);
if (lockStore.cacheResults()) {
enlist(this);
try {
Object value = locksCache.get(uri.toString());
Vector locksVector = null;
if (value == null) {
locksVector = new Vector();
locksCache.put(uri.toString(), locksVector);
} else {
locksVector = (Vector) value;
}
locksVector.addElement(lock.cloneObject());
} finally {
delist(this);
}
}
}
public void renewLock(Uri uri, NodeLock lock) throws ServiceAccessException, LockTokenNotFoundException {
super.renewLock(uri, lock);
if (lockStore.cacheResults()) {
enlist(this);
try {
Object value = locksCache.get(uri.toString());
Vector locksVector = null;
if (value != null) {
locksVector = (Vector) value;
boolean wasPresent = locksVector.removeElement(lock);
if (!wasPresent) {
throw new LockTokenNotFoundException(lock);
}
locksVector.addElement(lock.cloneObject());
}
} finally {
delist(this);
}
}
}
public void removeLock(Uri uri, NodeLock lock) throws ServiceAccessException, LockTokenNotFoundException {
super.removeLock(uri, lock);
if (lockStore.cacheResults()) {
enlist(this);
try {
Object value = locksCache.get(uri.toString());
Vector locksVector = null;
if (value != null) {
locksVector = (Vector) value;
boolean wasPresent = locksVector.removeElement(lock);
if (!wasPresent) {
throw new LockTokenNotFoundException(lock);
}
}
} finally {
delist(this);
}
}
}
public void killLock(Uri uri, NodeLock lock) throws ServiceAccessException, LockTokenNotFoundException {
super.killLock(uri, lock);
if (lockStore.cacheResults()) {
enlist(this);
try {
Object value = locksCache.get(uri.toString());
Vector locksVector = null;
if (value != null) {
locksVector = (Vector) value;
boolean wasPresent = locksVector.removeElement(lock);
if (!wasPresent) {
throw new LockTokenNotFoundException(lock);
}
}
} finally {
delist(this);
}
}
}
public Enumeration enumerateLocks(Uri uri) throws ServiceAccessException {
if (lockStore.cacheResults()) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
Object value = locksCache.get(uri.toString());
Vector locksVector = null;
if (value == null) {
locksVector = new Vector();
Enumeration lockList = lockStore.enumerateLocks(uri);
while (lockList.hasMoreElements()) {
NodeLock tempLock = (NodeLock) lockList.nextElement();
tempLock.validate(uri.toString());
locksVector.addElement(tempLock);
}
locksCache.put(uri.toString(), locksVector);
} else {
locksVector = (Vector) value;
}
return ((Vector) locksVector.clone()).elements();
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.enumerateLocks(uri);
}
}
public NodeRevisionDescriptors retrieveRevisionDescriptors(Uri uri)
throws ServiceAccessException, RevisionDescriptorNotFoundException {
if (revisionDescriptorsStore.cacheResults()) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
Object tempObject = descriptorsCache.get(uri.toString());
if (tempObject != null) {
return ((NodeRevisionDescriptors) tempObject).cloneObject();
} else {
NodeRevisionDescriptors revisionDescriptors =
revisionDescriptorsStore.retrieveRevisionDescriptors(uri);
descriptorsCache.put(uri.toString(), revisionDescriptors);
revisionDescriptors.validate(uri.toString());
return revisionDescriptors.cloneObject();
}
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.retrieveRevisionDescriptors(uri);
}
}
public void createRevisionDescriptors(Uri uri, NodeRevisionDescriptors revisionDescriptors)
throws ServiceAccessException {
super.createRevisionDescriptors(uri, revisionDescriptors);
if (revisionDescriptorsStore.cacheResults()) {
enlist(this);
try {
descriptorsCache.put(uri.toString(), revisionDescriptors.cloneObject());
} finally {
delist(this);
}
}
}
public void storeRevisionDescriptors(Uri uri, NodeRevisionDescriptors revisionDescriptors)
throws ServiceAccessException, RevisionDescriptorNotFoundException {
super.storeRevisionDescriptors(uri, revisionDescriptors);
if (revisionDescriptorsStore.cacheResults()) {
enlist(this);
try {
descriptorsCache.put(uri.toString(), revisionDescriptors.cloneObject());
} finally {
delist(this);
}
}
}
public void removeRevisionDescriptors(Uri uri) throws ServiceAccessException {
if (revisionDescriptorsStore.cacheResults()) {
enlist(this);
try {
descriptorsCache.remove(uri.toString());
} finally {
delist(this);
}
}
super.removeRevisionDescriptors(uri);
}
public NodeRevisionDescriptor retrieveRevisionDescriptor(Uri uri, NodeRevisionNumber revisionNumber)
throws ServiceAccessException, RevisionDescriptorNotFoundException {
if (revisionDescriptorStore.cacheResults()) {
if (isForceStoreEnlistment(uri)) {
enlist(this);
}
try {
Object result = descriptorCache.get(uri + "-" + revisionNumber);
if (result != null) {
return ((NodeRevisionDescriptor) result).cloneObject();
} else {
NodeRevisionDescriptor revisionDescriptor =
revisionDescriptorStore.retrieveRevisionDescriptor(uri, revisionNumber);
revisionDescriptor.validate();
descriptorCache.put(uri + "-" + revisionNumber, revisionDescriptor);
return revisionDescriptor.cloneObject();
}
} finally {
if (isForceStoreEnlistment(uri)) {
delist(this);
}
}
} else {
return super.retrieveRevisionDescriptor(uri, revisionNumber);
}
}
public void createRevisionDescriptor(Uri uri, NodeRevisionDescriptor revisionDescriptor)
throws ServiceAccessException {
super.createRevisionDescriptor(uri, revisionDescriptor);
if (revisionDescriptorStore.cacheResults()) {
enlist(this);
try {
descriptorCache.put(
uri + "-" + revisionDescriptor.getRevisionNumber(),
revisionDescriptor.cloneObject());
} finally {
delist(this);
}
}
}
public void storeRevisionDescriptor(Uri uri, NodeRevisionDescriptor revisionDescriptor)
throws ServiceAccessException, RevisionDescriptorNotFoundException {
super.storeRevisionDescriptor(uri, revisionDescriptor);
if (revisionDescriptorStore.cacheResults()) {
enlist(this);
try {
String key = uri + "-" + revisionDescriptor.getRevisionNumber();
descriptorCache.put(key, revisionDescriptor.cloneObject());
} finally {
delist(this);
}
}
}
public void removeRevisionDescriptor(Uri uri, NodeRevisionNumber number) throws ServiceAccessException {
super.removeRevisionDescriptor(uri, number);
if (revisionDescriptorStore.cacheResults()) {
enlist(this);
try {
descriptorCache.remove(uri + "-" + number);
} finally {
delist(this);
}
}
}
//
// overloaded XAResource methods for transaction support
//
public void forget(Xid xid) throws XAException {
Xid txId = (Xid) XidWrapper.wrap(xid);
activeTransactionBranch.set(null);
objectsCache.getTxCache().forget(txId);
permissionsCache.getTxCache().forget(txId);
locksCache.getTxCache().forget(txId);
descriptorsCache.getTxCache().forget(txId);
descriptorCache.getTxCache().forget(txId);
if (contentCache != null)
contentCache.getTxCache().forget(txId);
}
public void rollback(Xid xid) throws XAException {
Xid txId = (Xid) XidWrapper.wrap(xid);
activeTransactionBranch.set(null);
objectsCache.getTxCache().rollback(txId);
permissionsCache.getTxCache().rollback(txId);
locksCache.getTxCache().rollback(txId);
descriptorsCache.getTxCache().rollback(txId);
descriptorCache.getTxCache().rollback(txId);
if (contentCache != null)
contentCache.getTxCache().rollback(txId);
}
public void commit(Xid xid, boolean onePhase) throws XAException {
Xid txId = (Xid) XidWrapper.wrap(xid);
activeTransactionBranch.set(null);
objectsCache.getTxCache().commit(txId);
permissionsCache.getTxCache().commit(txId);
locksCache.getTxCache().commit(txId);
descriptorsCache.getTxCache().commit(txId);
descriptorCache.getTxCache().commit(txId);
if (contentCache != null)
contentCache.getTxCache().commit(txId);
}
public int prepare(Xid xid) throws XAException {
// failure is notifyed directly on transaction, so there is no need to check it here
return XA_OK;
}
public void start(Xid xid, int flags) throws XAException {
// XXX we do not suspend, so we do not resume
if (flags == TMNOFLAGS || flags == TMJOIN) {
Xid txId = (Xid) XidWrapper.wrap(xid);
activeTransactionBranch.set(txId);
objectsCache.getTxCache().start(txId);
permissionsCache.getTxCache().start(txId);
locksCache.getTxCache().start(txId);
descriptorsCache.getTxCache().start(txId);
descriptorCache.getTxCache().start(txId);
if (contentCache != null)
contentCache.getTxCache().start(txId);
}
}
public void end(Xid xid, int flags) throws XAException {
}
//
public String toString() {
return getName() + "(" + getClass().getName() + ")";
}
//
// have it outside ctor to make it overloadable
protected void init(
int globalObjectCacheSize,
int globalPermissionCacheSize,
int globalLockCacheSize,
int globalDescrtiptorsCacheSize,
int globalDescrtiptorCacheSize,
boolean contentCachingEnabled,
int globalContentCacheSize,
long contentCacheBytes,
int txContentCacheSize,
long txContentCacheBytes,
long maxByteSizePerEntry) {
try {
objectsCache = new TxCacheWrapper(globalObjectCacheSize, "object");
permissionsCache = new TxCacheWrapper(globalPermissionCacheSize, "permission");
locksCache = new TxCacheWrapper(globalLockCacheSize, "lock");
descriptorsCache = new TxCacheWrapper(globalDescrtiptorsCacheSize, "descriptors");
descriptorCache = new TxCacheWrapper(globalDescrtiptorCacheSize, "descriptor");
if (contentCachingEnabled) {
contentCache =
new TxContentCacheWrapper(
new ByteSizeLimitedObjectCache(
globalContentCacheSize,
txContentCacheSize,
contentCacheBytes,
txContentCacheBytes,
maxByteSizePerEntry,
getName() + ".content",
getLogger()));
} else {
contentCache = null;
}
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
// could be out of memory etc.
protected void fatalError(Error e) {
getLogger().log("Fatal error: " + e, LOG_CHANNEL, Logger.CRITICAL);
// XXX needed to guarantee, stack trace will be displayed
getLogger().log(e, LOG_CHANNEL, Logger.CRITICAL);
setRollbackOnly();
throw e;
}
// could be null pointer or any other programming error
protected void fatalError(RuntimeException re) {
getLogger().log("Fatal error: " + re, LOG_CHANNEL, Logger.CRITICAL);
// XXX needed to guarantee, stack trace will be displayed
getLogger().log(re, LOG_CHANNEL, Logger.CRITICAL);
setRollbackOnly();
throw re;
}
protected class TxCacheWrapper implements ObjectCache {
private TxLRUObjectCache txCache;
public TxCacheWrapper(TxLRUObjectCache txCache) {
this.txCache = txCache;
}
public TxCacheWrapper(int globalCacheSize, String name) {
this(new TxLRUObjectCache(globalCacheSize, getName() + "." + name, getLogger()));
}
public Object get(Object key) {
if (globalCacheOff)
return null;
try {
Xid txId = (Xid) activeTransactionBranch.get();
return txCache.get(txId, key);
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
// XXX will never be called, as fatalError will always throw a throwable, just satisfy compiler
return null;
}
public void put(Object key, Object value) {
if (globalCacheOff)
return;
try {
Xid txId = (Xid) activeTransactionBranch.get();
txCache.put(txId, key, value);
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
public void remove(Object key) {
if (globalCacheOff)
return;
try {
Xid txId = (Xid) activeTransactionBranch.get();
txCache.remove(txId, key);
getLogger().log("Removing content at '" + key + "' from cache", LOG_CHANNEL, Logger.DEBUG);
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
public void clear() {
try {
txCache.clear();
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
public TxLRUObjectCache getTxCache() {
return txCache;
}
}
protected class TxContentCacheWrapper extends TxCacheWrapper {
public TxContentCacheWrapper(ByteSizeLimitedObjectCache txCache) {
super(txCache);
}
/*
* Ensures that if revisionContent will be cached later, it will be accessible multiple times.
* It does so by copying its input stream into a byte array. To avoid excessively large byte
* arrays this is only done when revisionContent fits into the cache and will be cached later anyway.
* <br>
* <br>
* <em>Caution</em>: This method must be called before any other method modifies revisionContent.
*
*/
public void precache(NodeRevisionContent revisionContent, long byteSize) {
if (globalCacheOff)
return;
try {
Xid txId = (Xid) activeTransactionBranch.get();
if (((ByteSizeLimitedObjectCache) getTxCache()).canCache(txId, byteSize)) {
// buffer stream content into byte array for multiple access
revisionContent.getContentBytes();
}
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
public void putForRead(Object key, NodeRevisionContent revisionContent, long byteSize) {
if (globalCacheOff)
return;
try {
if (((ByteSizeLimitedObjectCache) getTxCache()).canCache(null, byteSize)) {
// buffer stream content into byte array for multiple access
revisionContent.getContentBytes();
((ByteSizeLimitedObjectCache) getTxCache()).put(null, key, revisionContent, byteSize);
getLogger().log(
"Globally caching content at '" + key + "' with " + byteSize + " bytes",
LOG_CHANNEL,
Logger.DEBUG);
}
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
public void put(Object key, NodeRevisionContent revisionContent, long byteSize) {
if (globalCacheOff)
return;
try {
Xid txId = (Xid) activeTransactionBranch.get();
if (((ByteSizeLimitedObjectCache) getTxCache()).canCache(txId, byteSize)) {
// buffer stream content into byte array for multiple access
revisionContent.getContentBytes();
((ByteSizeLimitedObjectCache) getTxCache()).put(txId, key, revisionContent, byteSize);
getLogger().log(
"Caching content at '" + key + "' with " + byteSize + " bytes",
LOG_CHANNEL,
Logger.DEBUG);
} else {
// if we can not cache it, we need to invalidate global entry upon commit
getTxCache().remove(txId, key);
}
} catch (Error e) {
fatalError(e);
} catch (RuntimeException re) {
fatalError(re);
}
}
}
}
1.1 jakarta-slide/lib/commons-collections.jar
<<Binary file>>
---------------------------------------------------------------------
To unsubscribe, e-mail: slide-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: slide-dev-help@jakarta.apache.org