001: /*
002: * Copyright Aduna (http://www.aduna-software.com/) (c) 2008.
003: *
004: * Licensed under the Aduna BSD-style license.
005: */
006: package org.openrdf.sail.rdbms.managers.base;
007:
008: import java.sql.SQLException;
009: import java.util.concurrent.atomic.AtomicInteger;
010:
011: import info.aduna.collections.LRUMap;
012:
013: import org.openrdf.sail.rdbms.managers.HashManager;
014: import org.openrdf.sail.rdbms.model.RdbmsValue;
015: import org.openrdf.sail.rdbms.schema.IdSequence;
016:
017: public abstract class ValueManagerBase<V extends RdbmsValue> extends
018: ManagerBase {
019: private LRUMap<Object, V> cache;
020: private HashManager hashes;
021: private AtomicInteger version = new AtomicInteger();
022: private IdSequence ids;
023:
024: public void setHashManager(HashManager hashes) {
025: this .hashes = hashes;
026: }
027:
028: public IdSequence getIdSequence() {
029: return ids;
030: }
031:
032: public void setIdSequence(IdSequence ids) {
033: this .ids = ids;
034: }
035:
036: public void init() {
037: cache = new LRUMap<Object, V>(getBatchSize());
038: }
039:
040: @Override
041: public void flush() throws SQLException, InterruptedException {
042: if (hashes != null) {
043: hashes.flush();
044: }
045: super .flush();
046: }
047:
048: public V findInCache(Object key) {
049: synchronized (cache) {
050: if (cache.containsKey(key))
051: return cache.get(key);
052: }
053: return null;
054: }
055:
056: public void cache(V value) throws SQLException,
057: InterruptedException {
058: if (value.isExpired(getIdVersion())) {
059: synchronized (cache) {
060: cache.put(key(value), value);
061: }
062: if (hashes != null) {
063: hashes.lookupId(value);
064: }
065: }
066: }
067:
068: public Number getInternalId(V value) throws SQLException,
069: InterruptedException {
070: if (value.isExpired(getIdVersion())) {
071: if (hashes == null) {
072: Number id = ids.idOf(value);
073: value.setInternalId(id);
074: value.setVersion(getIdVersion());
075: insert(id, value);
076: } else if (value.isExpired(getIdVersion())) {
077: hashes.assignId(value, getIdVersion());
078: }
079: }
080: return value.getInternalId();
081: }
082:
083: public int getIdVersion() {
084: return version.intValue()
085: + (hashes == null ? 0 : hashes.getIdVersion());
086: }
087:
088: public void removedStatements(int count, String condition)
089: throws SQLException {
090: if (expungeRemovedStatements(count, condition)) {
091: version.addAndGet(1);
092: }
093: }
094:
095: protected abstract int getBatchSize();
096:
097: protected abstract void insert(Number id, V value)
098: throws SQLException, InterruptedException;
099:
100: protected abstract Object key(V value);
101:
102: protected abstract boolean expungeRemovedStatements(int count,
103: String condition) throws SQLException;
104:
105: @Override
106: protected void optimize() throws SQLException {
107: if (hashes != null) {
108: hashes.optimize();
109: }
110: }
111:
112: }
|