This is an automated email from the ASF dual-hosted git repository.
dlmarion pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/accumulo.git
The following commit(s) were added to refs/heads/main by this push:
new 6e55e84003 Remove deprecated LRUBlockCache (#6596)
6e55e84003 is described below
commit 6e55e84003641dddc2ca165f4a2c273700513afb
Author: Amanda Villarreal <[email protected]>
AuthorDate: Tue Nov 17 07:10:29 2026 -0600
Remove deprecated LRUBlockCache (#6596)
---
.../core/file/blockfile/cache/lru/CachedBlock.java | 174 -----
.../file/blockfile/cache/lru/CachedBlockQueue.java | 111 ----
.../core/file/blockfile/cache/lru/HeapSize.java | 46 --
.../file/blockfile/cache/lru/LruBlockCache.java | 721 ---------------------
.../cache/lru/LruBlockCacheConfiguration.java | 243 -------
.../blockfile/cache/lru/LruBlockCacheManager.java | 51 --
.../cache/lru/SynchronousLoadingBlockCache.java | 138 ----
.../apache/accumulo/core/spi/cache/BlockCache.java | 6 +-
.../accumulo/core/spi/cache/BlockCacheManager.java | 14 +-
.../blockfile/cache/BlockCacheFactoryTest.java | 10 -
.../file/blockfile/cache/TestCachedBlockQueue.java | 199 ------
.../file/blockfile/cache/TestLruBlockCache.java | 552 ----------------
.../hadoopImpl/mapreduce/lib/ConfiguratorBase.java | 2 +-
13 files changed, 9 insertions(+), 2258 deletions(-)
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlock.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlock.java
deleted file mode 100644
index ff18e8ff6a..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlock.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import java.util.Objects;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.function.Supplier;
-
-import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
-import org.apache.accumulo.core.file.blockfile.cache.impl.SizeConstants;
-import org.apache.accumulo.core.spi.cache.CacheEntry.Weighable;
-
-/**
- * Represents an entry in the configurable block cache.
- *
- * <p>
- * Makes the block memory-aware with {@link HeapSize} and Comparable to sort
by access time for the
- * LRU. It also takes care of priority by either instantiating as in-memory or
handling the
- * transition from single to multiple access.
- */
-public class CachedBlock implements HeapSize, Comparable<CachedBlock> {
-
- public static final long PER_BLOCK_OVERHEAD =
- ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 *
SizeConstants.SIZEOF_LONG)
- + ClassSize.STRING + ClassSize.BYTE_BUFFER + ClassSize.REFERENCE);
-
- public enum BlockPriority {
- /**
- * Accessed a single time (used for scan-resistance)
- */
- SINGLE,
- /**
- * Accessed multiple times
- */
- MULTI,
- /**
- * Block from in-memory store
- */
- MEMORY
- }
-
- private final byte[] buffer;
- private final String blockName;
- private volatile long accessTime;
- private volatile long recordedSize;
- private BlockPriority priority;
- private Weighable index;
-
- public CachedBlock(String blockName, byte[] buf, long accessTime, boolean
inMemory) {
- this.buffer = buf;
- this.blockName = blockName;
- this.accessTime = accessTime;
- if (inMemory) {
- this.priority = BlockPriority.MEMORY;
- } else {
- this.priority = BlockPriority.SINGLE;
- }
- }
-
- /**
- * Block has been accessed. Update its local access time.
- */
- public void access(long accessTime) {
- this.accessTime = accessTime;
- if (this.priority == BlockPriority.SINGLE) {
- this.priority = BlockPriority.MULTI;
- }
- }
-
- @Override
- public long heapSize() {
- if (recordedSize < 0) {
- throw new IllegalStateException("Block was evicted: " + blockName);
- }
- return recordedSize;
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(accessTime);
- }
-
- @Override
- public boolean equals(Object obj) {
- return this == obj || (obj instanceof CachedBlock &&
compareTo((CachedBlock) obj) == 0);
- }
-
- @Override
- public int compareTo(CachedBlock that) {
- if (this.accessTime == that.accessTime) {
- return 0;
- }
- return this.accessTime < that.accessTime ? 1 : -1;
- }
-
- public String getName() {
- return this.blockName;
- }
-
- public BlockPriority getPriority() {
- return this.priority;
- }
-
- public byte[] getBuffer() {
- return buffer;
- }
-
- @SuppressWarnings("unchecked")
- public synchronized <T extends Weighable> T getIndex(Supplier<T> supplier) {
- if (index == null && recordedSize >= 0) {
- index = supplier.get();
- }
-
- return (T) index;
- }
-
- private synchronized long _recordSize(AtomicLong totalSize) {
- long indexSize = (index == null) ? 0 : index.weight();
- long newSize = ClassSize.align(blockName.length()) +
ClassSize.align(buffer.length)
- + PER_BLOCK_OVERHEAD + indexSize;
- long delta = newSize - recordedSize;
- recordedSize = newSize;
- return totalSize.addAndGet(delta);
- }
-
- /**
- * Attempt to record size if not evicted.
- *
- * @return -1 if evicted
- */
- synchronized long tryRecordSize(AtomicLong totalSize) {
- if (recordedSize >= 0) {
- return _recordSize(totalSize);
- }
-
- return -1;
- }
-
- public synchronized long recordSize(AtomicLong totalSize) {
- if (recordedSize >= 0) {
- return _recordSize(totalSize);
- }
-
- throw new IllegalStateException("Block was evicted: " + blockName);
- }
-
- public synchronized long evicted(AtomicLong totalSize) {
- if (recordedSize >= 0) {
- totalSize.addAndGet(recordedSize * -1);
- long tmp = recordedSize;
- recordedSize = -1;
- index = null;
- return tmp;
- }
-
- throw new IllegalStateException("Block was already evicted: " + blockName);
- }
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlockQueue.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlockQueue.java
deleted file mode 100644
index e42f457a20..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlockQueue.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import java.util.LinkedList;
-import java.util.Objects;
-import java.util.PriorityQueue;
-
-/**
- * A memory-bound queue that will grow until an element brings total size
>= maxSize. From then
- * on, only entries that are sorted larger than the smallest current entry
will be
- * inserted/replaced.
- *
- * <p>
- * Use this when you want to find the largest elements (according to their
ordering, not their heap
- * size) that consume as close to the specified maxSize as possible. Default
behavior is to grow
- * just above rather than just below specified max.
- *
- * <p>
- * Object used in this queue must implement {@link HeapSize} as well as {@link
Comparable}.
- */
-public class CachedBlockQueue implements HeapSize {
-
- private final PriorityQueue<CachedBlock> queue;
-
- private long heapSize;
- private final long maxSize;
-
- /**
- * @param maxSize the target size of elements in the queue
- * @param blockSize expected average size of blocks
- */
- public CachedBlockQueue(long maxSize, long blockSize) {
- int initialSize = (int) Math.ceil(maxSize / (double) blockSize);
- if (initialSize == 0) {
- initialSize++;
- }
- queue = new PriorityQueue<>(initialSize);
- heapSize = 0;
- this.maxSize = maxSize;
- }
-
- /**
- * Attempt to add the specified cached block to this queue.
- *
- * <p>
- * If the queue is smaller than the max size, or if the specified element is
ordered before the
- * smallest element in the queue, the element will be added to the queue.
Otherwise, there is no
- * side effect of this call.
- *
- * @param cb block to try to add to the queue
- */
- public void add(CachedBlock cb) {
- if (heapSize < maxSize) {
- queue.add(cb);
- heapSize += cb.heapSize();
- } else {
- CachedBlock head =
- Objects.requireNonNull(queue.peek(), "No cached blocks available
from queue");
- if (cb.compareTo(head) > 0) {
- heapSize += cb.heapSize();
- heapSize -= head.heapSize();
- if (heapSize > maxSize) {
- queue.poll();
- } else {
- heapSize += head.heapSize();
- }
- queue.add(cb);
- }
- }
- }
-
- /**
- * Get a sorted List of all elements in this queue, in descending order.
- *
- * @return list of cached elements in descending order
- */
- public CachedBlock[] get() {
- LinkedList<CachedBlock> blocks = new LinkedList<>();
- while (!queue.isEmpty()) {
- blocks.addFirst(queue.poll());
- }
- return blocks.toArray(new CachedBlock[0]);
- }
-
- /**
- * Total size of all elements in this queue.
- *
- * @return size of all elements currently in queue, in bytes
- */
- @Override
- public long heapSize() {
- return heapSize;
- }
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/HeapSize.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/HeapSize.java
deleted file mode 100644
index f3bbc9c823..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/HeapSize.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-/**
- * Implementations can be asked for an estimate of their size in bytes.
- * <p>
- * Useful for sizing caches. Its a given that implementation approximations do
not account for 32 vs
- * 64 bit nor for different VM implementations.
- * <p>
- * An Object's size is determined by the non-static data members in it, as
well as the fixed
- * {@link Object} overhead.
- * <p>
- * For example:
- *
- * <pre>
- * public class SampleObject implements HeapSize {
- * int[] numbers;
- * int x;
- * }
- * </pre>
- */
-public interface HeapSize {
- /**
- * @return Approximate 'exclusive deep size' of implementing object.
Includes count of payload and
- * hosting object sizings.
- */
- long heapSize();
-
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCache.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCache.java
deleted file mode 100644
index 2486bbe00d..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCache.java
+++ /dev/null
@@ -1,721 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-import static
org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize.CONCURRENT_HASHMAP;
-import static
org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize.CONCURRENT_HASHMAP_ENTRY;
-import static
org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize.CONCURRENT_HASHMAP_SEGMENT;
-
-import java.lang.ref.WeakReference;
-import java.util.Objects;
-import java.util.PriorityQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.function.Supplier;
-
-import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
-import org.apache.accumulo.core.file.blockfile.cache.impl.SizeConstants;
-import org.apache.accumulo.core.spi.cache.BlockCache;
-import org.apache.accumulo.core.spi.cache.CacheEntry;
-import org.apache.accumulo.core.util.threads.ThreadPools;
-import org.apache.accumulo.core.util.threads.Threads.AccumuloDaemonThread;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-/**
- * A block cache implementation that is memory-aware using {@link HeapSize},
memory-bound using an
- * LRU eviction algorithm, and concurrent: backed by a {@link
ConcurrentHashMap} and with a
- * non-blocking eviction thread giving constant-time {@link #cacheBlock} and
{@link #getBlock}
- * operations.
- *
- * <p>
- * Contains three levels of block priority to allow for scan-resistance and
in-memory families. A
- * block is added with an inMemory flag if necessary, otherwise a block
becomes a single access
- * priority. Once a blocked is accessed again, it changes to multiple access.
This is used to
- * prevent scans from thrashing the cache, adding a least-frequently-used
element to the eviction
- * algorithm.
- *
- * <p>
- * Each priority is given its own chunk of the total cache to ensure fairness
during eviction. Each
- * priority will retain close to its maximum size, however, if any priority is
not using its entire
- * chunk the others are able to grow beyond their chunk size.
- *
- * <p>
- * Instantiated at a minimum with the total size and average block size. All
sizes are in bytes. The
- * block size is not especially important as this cache is fully dynamic in
its sizing of blocks. It
- * is only used for pre-allocating data structures and in initial heap
estimation of the map.
- *
- * <p>
- * The detailed constructor defines the sizes for the three priorities (they
should total to the
- * maximum size defined). It also sets the levels that trigger and control the
eviction thread.
- *
- * <p>
- * The acceptable size is the cache size level which triggers the eviction
process to start. It
- * evicts enough blocks to get the size below the minimum size specified.
- *
- * <p>
- * Eviction happens in a separate thread and involves a single full-scan of
the map. It determines
- * how many bytes must be freed to reach the minimum size, and then while
scanning determines the
- * fewest least-recently-used blocks necessary from each of the three
priorities (would be 3 times
- * bytes to free). It then uses the priority chunk sizes to evict fairly
according to the relative
- * sizes and usage.
- */
-public final class LruBlockCache extends SynchronousLoadingBlockCache
- implements BlockCache, HeapSize {
-
- private static final Logger log =
LoggerFactory.getLogger(LruBlockCache.class);
-
- /** Statistics thread */
- static final int statThreadPeriod = 60;
-
- /** Concurrent map (the cache) */
- private final ConcurrentHashMap<String,CachedBlock> map;
-
- /** Eviction lock (locked when eviction in process) */
- private final ReentrantLock evictionLock = new ReentrantLock(true);
-
- /** Volatile boolean to track if we are in an eviction process or not */
- private volatile boolean evictionInProgress = false;
-
- /** Eviction thread */
- private final EvictionThread evictionThread;
-
- /** Statistics thread schedule pool (for heavy debugging, could remove) */
- private final ScheduledExecutorService scheduleThreadPool =
- ThreadPools.getServerThreadPools().createScheduledExecutorService(1,
"LRUBlockCacheStats");
-
- /** Current size of cache */
- private final AtomicLong size;
-
- /** Current number of cached elements */
- private final AtomicLong elements;
-
- /** Cache access count (sequential ID) */
- private final AtomicLong count;
-
- /** Cache statistics */
- private final CacheStats stats;
-
- /** Overhead of the structure itself */
- private final long overhead;
-
- private final LruBlockCacheConfiguration conf;
-
- /**
- * Default constructor. Specify maximum size and expected average block size
(approximation is
- * fine).
- *
- * <p>
- * All other factors will be calculated based on defaults specified in this
class.
- *
- * @param conf block cache configuration
- */
- @SuppressFBWarnings(value = "SC_START_IN_CTOR",
- justification = "bad practice to start threads in constructor; probably
needs rewrite")
- public LruBlockCache(final LruBlockCacheConfiguration conf) {
- this.conf = conf;
-
- int mapInitialSize = (int) Math.ceil(1.2 * conf.getMaxSize() /
conf.getBlockSize());
-
- map = new ConcurrentHashMap<>(mapInitialSize, conf.getMapLoadFactor(),
- conf.getMapConcurrencyLevel());
- this.stats = new CacheStats();
- this.count = new AtomicLong(0);
- this.elements = new AtomicLong(0);
- this.overhead =
- calculateOverhead(conf.getMaxSize(), conf.getBlockSize(),
conf.getMapConcurrencyLevel());
- this.size = new AtomicLong(this.overhead);
-
- if (conf.isUseEvictionThread()) {
- this.evictionThread = new EvictionThread(this);
- this.evictionThread.start();
- while (!this.evictionThread.running()) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException(ex);
- }
- }
- } else {
- this.evictionThread = null;
- }
- ScheduledFuture<?> future = this.scheduleThreadPool.scheduleAtFixedRate(
- new StatisticsThread(this), statThreadPeriod, statThreadPeriod,
SECONDS);
- ThreadPools.watchNonCriticalScheduledTask(future);
- }
-
- public long getOverhead() {
- return overhead;
- }
-
- /*
- * This class exists so that every cache entry does not have a reference to
the cache.
- */
- private class LruCacheEntry implements CacheEntry {
- private final CachedBlock block;
-
- LruCacheEntry(CachedBlock block) {
- this.block = block;
- }
-
- @Override
- public byte[] getBuffer() {
- return block.getBuffer();
- }
-
- @Override
- public <T extends Weighable> T getIndex(Supplier<T> supplier) {
- return block.getIndex(supplier);
- }
-
- @Override
- public void indexWeightChanged() {
- long newSize = block.tryRecordSize(size);
- if (newSize >= 0 && newSize > acceptableSize() && !evictionInProgress) {
- runEviction();
- }
- }
- }
-
- private CacheEntry wrap(CachedBlock cb) {
- if (cb == null) {
- return null;
- }
-
- return new LruCacheEntry(cb);
- }
-
- // BlockCache implementation
-
- /**
- * Cache the block with the specified name and buffer.
- * <p>
- * It is assumed this will NEVER be called on an already cached block. If
that is done, it is
- * assumed that you are reinserting the same exact block due to a race
condition and will update
- * the buffer but not modify the size of the cache.
- *
- * @param blockName block name
- * @param buf block buffer
- * @param inMemory if block is in-memory
- */
- public CacheEntry cacheBlock(String blockName, byte[] buf, boolean inMemory)
{
- CachedBlock cb = map.get(blockName);
- if (cb != null) {
- stats.duplicateReads();
- cb.access(count.incrementAndGet());
- } else {
- cb = new CachedBlock(blockName, buf, count.incrementAndGet(), inMemory);
- CachedBlock currCb = map.putIfAbsent(blockName, cb);
- if (currCb != null) {
- stats.duplicateReads();
- cb = currCb;
- cb.access(count.incrementAndGet());
- } else {
- // Actually added block to cache
- long newSize = cb.recordSize(size);
- elements.incrementAndGet();
- if (newSize > acceptableSize() && !evictionInProgress) {
- runEviction();
- }
- }
- }
-
- return wrap(cb);
- }
-
- /**
- * Cache the block with the specified name and buffer.
- * <p>
- * It is assumed this will NEVER be called on an already cached block. If
that is done, it is
- * assumed that you are reinserting the same exact block due to a race
condition and will update
- * the buffer but not modify the size of the cache.
- *
- * @param blockName block name
- * @param buf block buffer
- */
- @Override
- public CacheEntry cacheBlock(String blockName, byte[] buf) {
- return cacheBlock(blockName, buf, false);
- }
-
- /**
- * Get the buffer of the block with the specified name.
- *
- * @param blockName block name
- * @return buffer of specified block name, or null if not in cache
- */
- @Override
- public CacheEntry getBlock(String blockName) {
- CachedBlock cb = map.get(blockName);
- if (cb == null) {
- stats.miss();
- return null;
- }
- stats.hit();
- cb.access(count.incrementAndGet());
- return wrap(cb);
- }
-
- @Override
- protected CacheEntry getBlockNoStats(String blockName) {
- CachedBlock cb = map.get(blockName);
- if (cb != null) {
- cb.access(count.incrementAndGet());
- }
- return wrap(cb);
- }
-
- protected long evictBlock(CachedBlock block) {
- if (map.remove(block.getName()) != null) {
- elements.decrementAndGet();
- stats.evicted();
- return block.evicted(size);
- }
- return 0;
- }
-
- /**
- * Multi-threaded call to run the eviction process.
- */
- private void runEviction() {
- if (evictionThread == null) {
- evict();
- } else {
- evictionThread.evict();
- }
- }
-
- /**
- * Eviction method.
- */
- void evict() {
-
- // Ensure only one eviction at a time
- if (!evictionLock.tryLock()) {
- return;
- }
-
- try {
- evictionInProgress = true;
-
- long bytesToFree = size.get() - minSize();
-
- log.trace("Block cache LRU eviction started. Attempting to free {}
bytes", bytesToFree);
-
- if (bytesToFree <= 0) {
- return;
- }
-
- // Instantiate priority buckets
- BlockBucket bucketSingle = new BlockBucket(bytesToFree,
conf.getBlockSize(), singleSize());
- BlockBucket bucketMulti = new BlockBucket(bytesToFree,
conf.getBlockSize(), multiSize());
- BlockBucket bucketMemory = new BlockBucket(bytesToFree,
conf.getBlockSize(), memorySize());
-
- // Scan entire map putting into appropriate buckets
- for (CachedBlock cachedBlock : map.values()) {
- switch (cachedBlock.getPriority()) {
- case SINGLE:
- bucketSingle.add(cachedBlock);
- break;
- case MULTI:
- bucketMulti.add(cachedBlock);
- break;
- case MEMORY:
- bucketMemory.add(cachedBlock);
- break;
- }
- }
-
- PriorityQueue<BlockBucket> bucketQueue = new PriorityQueue<>(3);
-
- bucketQueue.add(bucketSingle);
- bucketQueue.add(bucketMulti);
- bucketQueue.add(bucketMemory);
-
- int remainingBuckets = 3;
- long bytesFreed = 0;
-
- BlockBucket bucket;
- while ((bucket = bucketQueue.poll()) != null) {
- long overflow = bucket.overflow();
- if (overflow > 0) {
- long bucketBytesToFree = Math.min(overflow,
- (long) Math.ceil((bytesToFree - bytesFreed) / (double)
remainingBuckets));
- bytesFreed += bucket.free(bucketBytesToFree);
- }
- remainingBuckets--;
- }
-
- float singleMB = ((float) bucketSingle.totalSize()) / ((float) (1024 *
1024));
- float multiMB = ((float) bucketMulti.totalSize()) / ((float) (1024 *
1024));
- float memoryMB = ((float) bucketMemory.totalSize()) / ((float) (1024 *
1024));
-
- log.trace(
- "Block cache LRU eviction completed. Freed {} bytes. Priority Sizes:"
- + " Single={}MB ({}), Multi={}MB ({}), Memory={}MB ({})",
- bytesFreed, singleMB, bucketSingle.totalSize(), multiMB,
bucketMulti.totalSize(),
- memoryMB, bucketMemory.totalSize());
-
- } finally {
- stats.evict();
- evictionInProgress = false;
- evictionLock.unlock();
- }
- }
-
- /**
- * Used to group blocks into priority buckets. There will be a BlockBucket
for each priority
- * (single, multi, memory). Once bucketed, the eviction algorithm takes the
appropriate number of
- * elements out of each according to configuration parameters and their
relatives sizes.
- */
- private class BlockBucket implements Comparable<BlockBucket> {
-
- private final CachedBlockQueue queue;
- private long totalSize;
- private final long bucketSize;
-
- public BlockBucket(long bytesToFree, long blockSize, long bucketSize) {
- this.bucketSize = bucketSize;
- queue = new CachedBlockQueue(bytesToFree, blockSize);
- totalSize = 0;
- }
-
- public void add(CachedBlock block) {
- totalSize += block.heapSize();
- queue.add(block);
- }
-
- public long free(long toFree) {
- CachedBlock[] blocks = queue.get();
- long freedBytes = 0;
- for (CachedBlock block : blocks) {
- freedBytes += evictBlock(block);
- if (freedBytes >= toFree) {
- return freedBytes;
- }
- }
- return freedBytes;
- }
-
- public long overflow() {
- return totalSize - bucketSize;
- }
-
- public long totalSize() {
- return totalSize;
- }
-
- @Override
- public int compareTo(BlockBucket that) {
- if (this.overflow() == that.overflow()) {
- return 0;
- }
- return this.overflow() > that.overflow() ? 1 : -1;
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(overflow());
- }
-
- @Override
- public boolean equals(Object that) {
- if (that instanceof BlockBucket) {
- return compareTo((BlockBucket) that) == 0;
- }
- return false;
- }
- }
-
- @Override
- public long getMaxHeapSize() {
- return getMaxSize();
- }
-
- @Override
- public long getMaxSize() {
- return this.conf.getMaxSize();
- }
-
- @Override
- public int getMaxEntrySize() {
- return (int) Math.min(Integer.MAX_VALUE, getMaxSize());
- }
-
- /**
- * Get the current size of this cache.
- *
- * @return current size in bytes
- */
- public long getCurrentSize() {
- return this.size.get();
- }
-
- /**
- * Get the current size of this cache.
- *
- * @return current size in bytes
- */
- public long getFreeSize() {
- return getMaxSize() - getCurrentSize();
- }
-
- /**
- * Get the size of this cache (number of cached blocks)
- *
- * @return number of cached blocks
- */
- public long size() {
- return this.elements.get();
- }
-
- /**
- * Get the number of eviction runs that have occurred
- */
- public long getEvictionCount() {
- return this.stats.getEvictionCount();
- }
-
- /**
- * Get the number of blocks that have been evicted during the lifetime of
this cache.
- */
- public long getEvictedCount() {
- return this.stats.getEvictedCount();
- }
-
- /**
- * Eviction thread. Sits in waiting state until an eviction is triggered
when the cache size grows
- * above the acceptable level.
- *
- * <p>
- * Thread is triggered into action by {@link LruBlockCache#runEviction()}
- */
- private static class EvictionThread extends AccumuloDaemonThread {
- private final WeakReference<LruBlockCache> cache;
- private boolean running = false;
-
- public EvictionThread(LruBlockCache cache) {
- super("LruBlockCache.EvictionThread");
- this.cache = new WeakReference<>(cache);
- }
-
- public synchronized boolean running() {
- return running;
- }
-
- @SuppressFBWarnings(value = "UW_UNCOND_WAIT", justification = "eviction is
resumed by caller")
- @Override
- public void run() {
- while (true) {
- synchronized (this) {
- running = true;
- try {
- this.wait();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- LruBlockCache cache = this.cache.get();
- if (cache == null) {
- break;
- }
- cache.evict();
- }
- }
-
- @SuppressFBWarnings(value = "NN_NAKED_NOTIFY", justification = "eviction
is resumed by caller")
- public void evict() {
- synchronized (this) {
- this.notify();
- }
- }
- }
-
- /*
- * Statistics thread. Periodically prints the cache statistics to the log.
- */
- private static class StatisticsThread extends AccumuloDaemonThread {
- final LruBlockCache lru;
-
- public StatisticsThread(LruBlockCache lru) {
- super("LruBlockCache.StatisticsThread");
- this.lru = lru;
- }
-
- @Override
- public void run() {
- lru.logStats();
- }
- }
-
- public void logStats() {
- // Log size
- long totalSize = heapSize();
- long freeSize = this.conf.getMaxSize() - totalSize;
- float sizeMB = ((float) totalSize) / ((float) (1024 * 1024));
- float freeMB = ((float) freeSize) / ((float) (1024 * 1024));
- float maxMB = ((float) this.conf.getMaxSize()) / ((float) (1024 * 1024));
- log.debug(
- "Cache Stats: {} Sizes: Total={}MB ({}), Free={}MB ({}), Max={}MB"
- + " ({}), Counts: Blocks={}, Access={}, Hit={}, Miss={},
Evictions={},"
- + " Evicted={},Ratios: Hit Ratio={}%, Miss Ratio={}%,
Evicted/Run={},"
- + " Duplicate Reads={}",
- conf.getCacheType(), sizeMB, totalSize, freeMB, freeSize, maxMB,
this.conf.getMaxSize(),
- size(), stats.requestCount(), stats.hitCount(), stats.getMissCount(),
- stats.getEvictionCount(), stats.getEvictedCount(), stats.getHitRatio()
* 100,
- stats.getMissRatio() * 100, stats.evictedPerEviction(),
stats.getDuplicateReads());
- }
-
- /**
- * Get counter statistics for this cache.
- *
- * <p>
- * Includes: total accesses, hits, misses, evicted blocks, and runs of the
eviction processes.
- */
- @Override
- public CacheStats getStats() {
- return this.stats;
- }
-
- public static class CacheStats implements BlockCache.Stats {
- private final AtomicLong accessCount = new AtomicLong(0);
- private final AtomicLong hitCount = new AtomicLong(0);
- private final AtomicLong missCount = new AtomicLong(0);
- private final AtomicLong evictionCount = new AtomicLong(0);
- private final AtomicLong evictedCount = new AtomicLong(0);
- private final AtomicLong duplicateReads = new AtomicLong(0);
-
- public void miss() {
- missCount.incrementAndGet();
- accessCount.incrementAndGet();
- }
-
- public void hit() {
- hitCount.incrementAndGet();
- accessCount.incrementAndGet();
- }
-
- public void evict() {
- evictionCount.incrementAndGet();
- }
-
- public void duplicateReads() {
- duplicateReads.incrementAndGet();
- }
-
- public void evicted() {
- evictedCount.incrementAndGet();
- }
-
- @Override
- public long requestCount() {
- return accessCount.get();
- }
-
- @Override
- public long evictionCount() {
- return getEvictedCount();
- }
-
- public long getMissCount() {
- return missCount.get();
- }
-
- @Override
- public long hitCount() {
- return hitCount.get();
- }
-
- public long getEvictionCount() {
- return evictionCount.get();
- }
-
- public long getDuplicateReads() {
- return duplicateReads.get();
- }
-
- public long getEvictedCount() {
- return evictedCount.get();
- }
-
- public double getHitRatio() {
- return ((float) hitCount() / (float) requestCount());
- }
-
- public double getMissRatio() {
- return ((float) getMissCount() / (float) requestCount());
- }
-
- public double evictedPerEviction() {
- return (float) getEvictedCount() / (float) getEvictionCount();
- }
- }
-
- public static final long CACHE_FIXED_OVERHEAD =
- ClassSize.align((3 * SizeConstants.SIZEOF_LONG) + (8 *
ClassSize.REFERENCE)
- + (5 * SizeConstants.SIZEOF_FLOAT) + SizeConstants.SIZEOF_BOOLEAN +
ClassSize.OBJECT);
-
- // HeapSize implementation
- @Override
- public long heapSize() {
- return getCurrentSize();
- }
-
- public static long calculateOverhead(long maxSize, long blockSize, int
concurrency) {
- long entryPart = Math.round(maxSize * 1.2 / blockSize) *
CONCURRENT_HASHMAP_ENTRY;
- long segmentPart = (long) concurrency * CONCURRENT_HASHMAP_SEGMENT;
- return CACHE_FIXED_OVERHEAD + CONCURRENT_HASHMAP + entryPart + segmentPart;
- }
-
- // Simple calculators of sizes given factors and maxSize
-
- private long acceptableSize() {
- return (long) Math.floor(this.conf.getMaxSize() *
this.conf.getAcceptableFactor());
- }
-
- private long minSize() {
- return (long) Math.floor(this.conf.getMaxSize() *
this.conf.getMinFactor());
- }
-
- private long singleSize() {
- return (long) Math
- .floor(this.conf.getMaxSize() * this.conf.getSingleFactor() *
this.conf.getMinFactor());
- }
-
- private long multiSize() {
- return (long) Math
- .floor(this.conf.getMaxSize() * this.conf.getMultiFactor() *
this.conf.getMinFactor());
- }
-
- private long memorySize() {
- return (long) Math
- .floor(this.conf.getMaxSize() * this.conf.getMemoryFactor() *
this.conf.getMinFactor());
- }
-
- public void shutdown() {
- this.scheduleThreadPool.shutdown();
- }
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheConfiguration.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheConfiguration.java
deleted file mode 100644
index bcc2ea9214..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheConfiguration.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-
-import org.apache.accumulo.core.conf.Property;
-import
org.apache.accumulo.core.file.blockfile.cache.impl.BlockCacheConfiguration;
-import org.apache.accumulo.core.spi.cache.BlockCacheManager.Configuration;
-import org.apache.accumulo.core.spi.cache.CacheType;
-
-import com.google.common.base.Preconditions;
-
-public final class LruBlockCacheConfiguration {
-
- public static final String PROPERTY_PREFIX = "lru";
-
- /* Default Configuration Parameters */
-
- /** Backing Concurrent Map Configuration */
- public static final Float DEFAULT_LOAD_FACTOR = 0.75f;
- public static final Integer DEFAULT_CONCURRENCY_LEVEL = 16;
-
- /** Eviction thresholds */
- public static final Float DEFAULT_MIN_FACTOR = 0.75f;
- public static final Float DEFAULT_ACCEPTABLE_FACTOR = 0.85f;
-
- /** Priority buckets */
- public static final Float DEFAULT_SINGLE_FACTOR = 0.25f;
- public static final Float DEFAULT_MULTI_FACTOR = 0.50f;
- public static final Float DEFAULT_MEMORY_FACTOR = 0.25f;
-
- // property names
- public static final String ACCEPTABLE_FACTOR_PROPERTY = "acceptable.factor";
- public static final String MIN_FACTOR_PROPERTY = "min.factor";
- public static final String SINGLE_FACTOR_PROPERTY = "single.factor";
- public static final String MULTI_FACTOR_PROPERTY = "multi.factor";
- public static final String MEMORY_FACTOR_PROPERTY = "memory.factor";
- public static final String MAP_LOAD_PROPERTY = "map.load";
- public static final String MAP_CONCURRENCY_PROPERTY = "map.concurrency";
- public static final String EVICTION_THREAD_PROPERTY = "eviction.thread";
-
- /** Acceptable size of cache (no evictions if size < acceptable) */
- private final float acceptableFactor;
-
- /** Minimum threshold of cache (when evicting, evict until size < min) */
- private final float minFactor;
-
- /** Single access bucket size */
- private final float singleFactor;
-
- /** Multiple access bucket size */
- private final float multiFactor;
-
- /** In-memory bucket size */
- private final float memoryFactor;
-
- /** LruBlockCache cache = new LruBlockCache **/
- private final float mapLoadFactor;
-
- /** LruBlockCache cache = new LruBlockCache **/
- private final int mapConcurrencyLevel;
-
- private final boolean useEvictionThread;
-
- private final Configuration conf;
-
- private final Map<String,String> props;
-
- private final CacheType type;
-
- private Optional<String> get(String k) {
- return Optional.ofNullable(props.get(k));
- }
-
- public LruBlockCacheConfiguration(Configuration conf, CacheType type) {
-
- this.type = type;
- this.conf = conf;
- this.props = conf.getProperties(PROPERTY_PREFIX, type);
-
- this.acceptableFactor =
get(ACCEPTABLE_FACTOR_PROPERTY).map(Float::valueOf).filter(f -> f > 0)
- .orElse(DEFAULT_ACCEPTABLE_FACTOR);
- this.minFactor =
- get(MIN_FACTOR_PROPERTY).map(Float::valueOf).filter(f -> f >
0).orElse(DEFAULT_MIN_FACTOR);
- this.singleFactor =
get(SINGLE_FACTOR_PROPERTY).map(Float::valueOf).filter(f -> f > 0)
- .orElse(DEFAULT_SINGLE_FACTOR);
- this.multiFactor = get(MULTI_FACTOR_PROPERTY).map(Float::valueOf).filter(f
-> f > 0)
- .orElse(DEFAULT_MULTI_FACTOR);
- this.memoryFactor =
get(MEMORY_FACTOR_PROPERTY).map(Float::valueOf).filter(f -> f > 0)
- .orElse(DEFAULT_MEMORY_FACTOR);
- this.mapLoadFactor =
- get(MAP_LOAD_PROPERTY).map(Float::valueOf).filter(f -> f >
0).orElse(DEFAULT_LOAD_FACTOR);
- this.mapConcurrencyLevel =
get(MAP_CONCURRENCY_PROPERTY).map(Integer::valueOf)
- .filter(i -> i > 0).orElse(DEFAULT_CONCURRENCY_LEVEL);
- this.useEvictionThread =
get(EVICTION_THREAD_PROPERTY).map(Boolean::valueOf).orElse(true);
-
- if (this.getSingleFactor() + this.getMultiFactor() +
this.getMemoryFactor() != 1) {
- throw new IllegalArgumentException("Single, multi, and memory factors
should total 1.0");
- }
- if (this.getMinFactor() >= this.getAcceptableFactor()) {
- throw new IllegalArgumentException("minFactor must be smaller than
acceptableFactor");
- }
- if (this.getMinFactor() >= 1.0f || this.getAcceptableFactor() >= 1.0f) {
- throw new IllegalArgumentException("all factors must be < 1");
- }
- }
-
- public float getAcceptableFactor() {
- return acceptableFactor;
- }
-
- public float getMinFactor() {
- return minFactor;
- }
-
- public float getSingleFactor() {
- return singleFactor;
- }
-
- public float getMultiFactor() {
- return multiFactor;
- }
-
- public float getMemoryFactor() {
- return memoryFactor;
- }
-
- public float getMapLoadFactor() {
- return mapLoadFactor;
- }
-
- public int getMapConcurrencyLevel() {
- return mapConcurrencyLevel;
- }
-
- public boolean isUseEvictionThread() {
- return useEvictionThread;
- }
-
- public static class Builder {
- private final Map<String,String> props = new HashMap<>();
- private final String prefix;
-
- private Builder(String prefix) {
- this.prefix = prefix;
- }
-
- private void set(String prop, float val) {
- props.put(prefix + prop, Float.toString(val));
- }
-
- public Builder acceptableFactor(float af) {
- Preconditions.checkArgument(af > 0);
- set(ACCEPTABLE_FACTOR_PROPERTY, af);
- return this;
- }
-
- public Builder minFactor(float mf) {
- Preconditions.checkArgument(mf > 0);
- set(MIN_FACTOR_PROPERTY, mf);
- return this;
- }
-
- public Builder singleFactor(float sf) {
- Preconditions.checkArgument(sf > 0);
- set(SINGLE_FACTOR_PROPERTY, sf);
- return this;
- }
-
- public Builder multiFactor(float mf) {
- Preconditions.checkArgument(mf > 0);
- set(MULTI_FACTOR_PROPERTY, mf);
- return this;
- }
-
- public Builder memoryFactor(float mf) {
- Preconditions.checkArgument(mf > 0);
- set(MEMORY_FACTOR_PROPERTY, mf);
- return this;
- }
-
- public Builder mapConcurrencyLevel(int mcl) {
- Preconditions.checkArgument(mcl > 0);
- props.put(prefix + MAP_CONCURRENCY_PROPERTY, mcl + "");
- return this;
- }
-
- public Builder useEvictionThread(boolean uet) {
- props.put(prefix + EVICTION_THREAD_PROPERTY, uet + "");
- return this;
- }
-
- public Map<String,String> buildMap() {
- return Map.copyOf(props);
- }
- }
-
- public static Builder builder(Property serverPrefix, CacheType ct) {
- return new Builder(
- BlockCacheConfiguration.getFullyQualifiedPropertyPrefix(serverPrefix,
PROPERTY_PREFIX, ct));
- }
-
- @Override
- public String toString() {
- return super.toString() + ", acceptableFactor: " +
this.getAcceptableFactor() + ", minFactor: "
- + this.getMinFactor() + ", singleFactor: " + this.getSingleFactor() +
", multiFactor: "
- + this.getMultiFactor() + ", memoryFactor: " + this.getMemoryFactor()
+ ", mapLoadFactor: "
- + this.getMapLoadFactor() + ", mapConcurrencyLevel: " +
this.getMapConcurrencyLevel()
- + ", useEvictionThread: " + this.isUseEvictionThread();
- }
-
- public long getMaxSize() {
- return conf.getMaxSize(type);
- }
-
- public CacheType getCacheType() {
- return type;
- }
-
- public long getBlockSize() {
- return conf.getBlockSize();
- }
-
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheManager.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheManager.java
deleted file mode 100644
index d8bb5bc552..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/LruBlockCacheManager.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import org.apache.accumulo.core.spi.cache.BlockCache;
-import org.apache.accumulo.core.spi.cache.BlockCacheManager;
-import org.apache.accumulo.core.spi.cache.CacheType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Deprecated(since = "4.0.0")
-public class LruBlockCacheManager extends BlockCacheManager {
-
- private static final Logger LOG =
LoggerFactory.getLogger(LruBlockCacheManager.class);
-
- @Override
- protected BlockCache createCache(Configuration conf, CacheType type) {
- LruBlockCacheConfiguration cc = new LruBlockCacheConfiguration(conf, type);
- LOG.info("Creating {} cache with configuration {}", type, cc);
- LOG.warn("This cache implementation is deprecated and will be remove in
future releases.");
- return new LruBlockCache(cc);
- }
-
- @Override
- public void stop() {
- for (CacheType type : CacheType.values()) {
- LruBlockCache cache = ((LruBlockCache) this.getBlockCache(type));
- if (cache != null) {
- cache.shutdown();
- }
- }
- super.stop();
- }
-
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/SynchronousLoadingBlockCache.java
b/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/SynchronousLoadingBlockCache.java
deleted file mode 100644
index df27c290ca..0000000000
---
a/core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/SynchronousLoadingBlockCache.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache.lru;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.apache.accumulo.core.spi.cache.BlockCache;
-import org.apache.accumulo.core.spi.cache.CacheEntry;
-
-/**
- * This class implements loading in such a way that load operations for the
same block will not run
- * concurrently.
- */
-public abstract class SynchronousLoadingBlockCache implements BlockCache {
-
- private final Lock[] loadLocks;
-
- /**
- * @param numLocks this controls how many load operations can run
concurrently
- */
- SynchronousLoadingBlockCache(int numLocks) {
- loadLocks = new Lock[numLocks];
- for (int i = 0; i < loadLocks.length; i++) {
- loadLocks[i] = new ReentrantLock(true);
- }
- }
-
- public SynchronousLoadingBlockCache() {
- this(5003);
- }
-
- private Map<String,byte[]> resolveDependencies(Map<String,Loader>
loaderDeps) {
- Map<String,byte[]> depData;
-
- switch (loaderDeps.size()) {
- case 0:
- depData = Collections.emptyMap();
- break;
- case 1: {
- Entry<String,Loader> entry = loaderDeps.entrySet().iterator().next();
- CacheEntry dce = getBlock(entry.getKey(), entry.getValue());
- if (dce == null) {
- depData = null;
- } else {
- depData = Collections.singletonMap(entry.getKey(), dce.getBuffer());
- }
- break;
- }
- default:
- depData = new HashMap<>();
- Set<Entry<String,Loader>> es = loaderDeps.entrySet();
- for (Entry<String,Loader> entry : es) {
- CacheEntry dce = getBlock(entry.getKey(), entry.getValue());
- if (dce == null) {
- depData = null;
- break;
- }
-
- depData.put(entry.getKey(), dce.getBuffer());
- }
- break;
- }
-
- return depData;
- }
-
- /**
- * Get the maximum size of an individual cache entry.
- */
- protected abstract int getMaxEntrySize();
-
- /**
- * Get a block from the cache without changing any stats the cache is
keeping.
- */
- protected abstract CacheEntry getBlockNoStats(String blockName);
-
- @Override
- public CacheEntry getBlock(String blockName, Loader loader) {
-
- CacheEntry ce = getBlock(blockName);
- if (ce != null) {
- return ce;
- }
-
- // intentionally done before getting lock
- Map<String,byte[]> depData = resolveDependencies(loader.getDependencies());
- if (depData == null) {
- return null;
- }
-
- int lockIndex = (blockName.hashCode() & 0x7fffffff) % loadLocks.length;
- Lock loadLock = loadLocks[lockIndex];
-
- loadLock.lock();
- try {
-
- // check again after getting lock, could have loaded while waiting on
lock
- ce = getBlockNoStats(blockName);
- if (ce != null) {
- return ce;
- }
-
- // not in cache so load data
- byte[] data = loader.load(getMaxEntrySize(), depData);
- if (data == null) {
- return null;
- }
-
- // attempt to add data to cache
- return cacheBlock(blockName, data);
- } finally {
- loadLock.unlock();
- }
- }
-
-}
diff --git
a/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCache.java
b/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCache.java
index f55b788050..d029e56077 100644
--- a/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCache.java
+++ b/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCache.java
@@ -20,8 +20,6 @@ package org.apache.accumulo.core.spi.cache;
import java.util.Map;
-import
org.apache.accumulo.core.file.blockfile.cache.lru.SynchronousLoadingBlockCache;
-
/**
* Block cache interface.
*
@@ -63,10 +61,8 @@ public interface BlockCache {
}
/**
- * This method allows a cache to prevent concurrent loads of the same block.
However a cache
+ * This method allows a cache to prevent concurrent loads of the same block.
However, a cache
* implementation is not required to prevent concurrent loads.
- * {@link SynchronousLoadingBlockCache} is an abstract class that a cache
can extent which does
- * prevent concurrent loading of the same block.
*
*
* @param blockName Block name to fetch
diff --git
a/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCacheManager.java
b/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCacheManager.java
index 4d462f009b..4834ef2aae 100644
---
a/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCacheManager.java
+++
b/core/src/main/java/org/apache/accumulo/core/spi/cache/BlockCacheManager.java
@@ -83,16 +83,16 @@ public abstract class BlockCacheManager {
* running in a tserver.
*
* <pre>
- * tserver.cache.config.lru.default.evictAfter=3600
- * tserver.cache.config.lru.default.loadFactor=.75
- * tserver.cache.config.lru.index.loadFactor=.55
- * tserver.cache.config.lru.data.loadFactor=.65
+ * tserver.cache.config.myplugin.default.evictAfter=3600
+ * tserver.cache.config.myplugin.default.loadFactor=.75
+ * tserver.cache.config.myplugin.index.loadFactor=.55
+ * tserver.cache.config.myplugin.data.loadFactor=.65
* </pre>
*
* <p>
- * If this method is called with {@code prefix=lru} and {@code type=INDEX}
then it would return
- * a map with the following key values. The load factor setting for index
overrides the default
- * value.
+ * If this method is called with {@code prefix=myplugin} and {@code
type=INDEX} then it would
+ * return a map with the following key values. The load factor setting for
index overrides the
+ * default value.
*
* <pre>
* evictAfter=3600
diff --git
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/BlockCacheFactoryTest.java
b/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/BlockCacheFactoryTest.java
index c697ca17a2..e26c9e909e 100644
---
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/BlockCacheFactoryTest.java
+++
b/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/BlockCacheFactoryTest.java
@@ -25,7 +25,6 @@ import org.apache.accumulo.core.conf.DefaultConfiguration;
import org.apache.accumulo.core.conf.Property;
import
org.apache.accumulo.core.file.blockfile.cache.impl.BlockCacheConfiguration;
import
org.apache.accumulo.core.file.blockfile.cache.impl.BlockCacheManagerFactory;
-import org.apache.accumulo.core.file.blockfile.cache.lru.LruBlockCacheManager;
import
org.apache.accumulo.core.file.blockfile.cache.tinylfu.TinyLfuBlockCacheManager;
import org.apache.accumulo.core.spi.cache.BlockCacheManager;
import org.apache.accumulo.core.spi.cache.CacheType;
@@ -33,15 +32,6 @@ import org.junit.jupiter.api.Test;
public class BlockCacheFactoryTest {
- @Test
- @SuppressWarnings("deprecation")
- public void testCreateLruBlockCacheFactory() throws Exception {
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManagerFactory.getInstance(cc);
- }
-
@Test
public void testCreateTinyLfuBlockCacheFactory() throws Exception {
DefaultConfiguration dc = DefaultConfiguration.getInstance();
diff --git
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestCachedBlockQueue.java
b/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestCachedBlockQueue.java
deleted file mode 100644
index 7739c0f247..0000000000
---
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestCachedBlockQueue.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.stream.Collectors;
-
-import org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlockQueue;
-import org.junit.jupiter.api.Test;
-
-public class TestCachedBlockQueue {
- @Test
- public void testLargeBlock() {
- CachedBlockQueue queue = new CachedBlockQueue(10000L, 1000L);
- CachedBlock cb1 = new CachedBlock(10001L, "cb1", 1L);
- queue.add(cb1);
-
- List<org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock> blocks
= getList(queue);
- assertEquals("cb1", Objects.requireNonNull(blocks.get(0)).getName());
- }
-
- @Test
- public void testAddNewerBlock() {
- CachedBlockQueue queue = new CachedBlockQueue(10000L, 1000L);
-
- AtomicLong sum = new AtomicLong();
-
- CachedBlock cb1 = new CachedBlock(5000L, "cb1", 1L);
- cb1.recordSize(sum);
- CachedBlock cb2 = new CachedBlock(5000, "cb2", 2L);
- cb2.recordSize(sum);
- CachedBlock cb3 = new CachedBlock(5000, "cb3", 3L);
- cb3.recordSize(sum);
-
- queue.add(cb1);
- queue.add(cb2);
- queue.add(cb3);
-
- List<org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock> blocks
= getList(queue);
-
- assertEquals(2, blocks.size());
-
- long expectedSize = cb1.heapSize() + cb2.heapSize();
- assertEquals(expectedSize, queue.heapSize());
- assertEquals(expectedSize, sum.get() - cb3.heapSize());
-
- assertEquals(List.of("cb1", "cb2"),
- blocks.stream().map(cb -> cb.getName()).collect(Collectors.toList()));
- }
-
- @Test
- public void testQueue() {
- AtomicLong sum = new AtomicLong();
- CachedBlock cb1 = new CachedBlock(1000, "cb1", 1);
- cb1.recordSize(sum);
- CachedBlock cb2 = new CachedBlock(1500, "cb2", 2);
- cb2.recordSize(sum);
- CachedBlock cb3 = new CachedBlock(1000, "cb3", 3);
- cb3.recordSize(sum);
- CachedBlock cb4 = new CachedBlock(1500, "cb4", 4);
- cb4.recordSize(sum);
- CachedBlock cb5 = new CachedBlock(1000, "cb5", 5);
- cb5.recordSize(sum);
- CachedBlock cb6 = new CachedBlock(1750, "cb6", 6);
- cb6.recordSize(sum);
- CachedBlock cb7 = new CachedBlock(1000, "cb7", 7);
- cb7.recordSize(sum);
- CachedBlock cb8 = new CachedBlock(1500, "cb8", 8);
- cb8.recordSize(sum);
- CachedBlock cb9 = new CachedBlock(1000, "cb9", 9);
- cb9.recordSize(sum);
- CachedBlock cb10 = new CachedBlock(1500, "cb10", 10);
- cb10.recordSize(sum);
-
- CachedBlockQueue queue = new CachedBlockQueue(10000, 1000);
-
- queue.add(cb1);
- queue.add(cb2);
- queue.add(cb3);
- queue.add(cb4);
- queue.add(cb5);
- queue.add(cb6);
- queue.add(cb7);
- queue.add(cb8);
- queue.add(cb9);
- queue.add(cb10);
-
- // We expect cb1 through cb8 to be in the queue
- long expectedSize = cb1.heapSize() + cb2.heapSize() + cb3.heapSize() +
cb4.heapSize()
- + cb5.heapSize() + cb6.heapSize() + cb7.heapSize() + cb8.heapSize();
-
- assertEquals(expectedSize, queue.heapSize());
- assertEquals(expectedSize, sum.get() - cb9.heapSize() - cb10.heapSize());
-
- List<org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock> blocks
= getList(queue);
-
- assertEquals(List.of("cb1", "cb2", "cb3", "cb4", "cb5", "cb6", "cb7",
"cb8"),
- blocks.stream().map(cb -> cb.getName()).collect(Collectors.toList()));
- }
-
- @Test
- public void testQueueSmallBlockEdgeCase() {
-
- AtomicLong sum = new AtomicLong();
- CachedBlock cb1 = new CachedBlock(1000, "cb1", 1);
- cb1.recordSize(sum);
- CachedBlock cb2 = new CachedBlock(1500, "cb2", 2);
- cb2.recordSize(sum);
- CachedBlock cb3 = new CachedBlock(1000, "cb3", 3);
- cb3.recordSize(sum);
- CachedBlock cb4 = new CachedBlock(1500, "cb4", 4);
- cb4.recordSize(sum);
- CachedBlock cb5 = new CachedBlock(1000, "cb5", 5);
- cb5.recordSize(sum);
- CachedBlock cb6 = new CachedBlock(1750, "cb6", 6);
- cb6.recordSize(sum);
- CachedBlock cb7 = new CachedBlock(1000, "cb7", 7);
- cb7.recordSize(sum);
- CachedBlock cb8 = new CachedBlock(1500, "cb8", 8);
- cb8.recordSize(sum);
- CachedBlock cb9 = new CachedBlock(1000, "cb9", 9);
- cb9.recordSize(sum);
- CachedBlock cb10 = new CachedBlock(1500, "cb10", 10);
- cb10.recordSize(sum);
-
- // validate that sum was not improperly added to heapSize in recordSize
method.
- assertEquals(cb3.heapSize(), cb7.heapSize());
-
- CachedBlockQueue queue = new CachedBlockQueue(10000, 1000);
-
- queue.add(cb1);
- queue.add(cb2);
- queue.add(cb3);
- queue.add(cb4);
- queue.add(cb5);
- queue.add(cb6);
- queue.add(cb7);
- queue.add(cb8);
- queue.add(cb9);
- queue.add(cb10);
-
- CachedBlock cb0 = new CachedBlock(10 + CachedBlock.PER_BLOCK_OVERHEAD,
"cb0", 0);
- queue.add(cb0);
-
- // This is older, so we must include it, but it will not end up kicking
- // anything out because (heapSize - cb8.heapSize + cb0.heapSize < maxSize)
- // and we must always maintain heapSize >= maxSize once we achieve it.
-
- // We expect cb0 through cb8 to be in the queue
- long expectedSize = cb1.heapSize() + cb2.heapSize() + cb3.heapSize() +
cb4.heapSize()
- + cb5.heapSize() + cb6.heapSize() + cb7.heapSize() + cb8.heapSize() +
cb0.heapSize();
-
- assertEquals(expectedSize, queue.heapSize());
- assertEquals(expectedSize, sum.get() - cb9.heapSize() - cb10.heapSize());
-
- List<org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock> blocks
= getList(queue);
-
- assertEquals(List.of("cb0", "cb1", "cb2", "cb3", "cb4", "cb5", "cb6",
"cb7", "cb8"),
- blocks.stream().map(cb -> cb.getName()).collect(Collectors.toList()));
- }
-
- private static class CachedBlock
- extends org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock {
- public CachedBlock(long heapSize, String name, long accessTime) {
- super(name, new byte[(int) (heapSize - CachedBlock.PER_BLOCK_OVERHEAD)],
accessTime, false);
- }
- }
-
- /**
- * Get a sorted List of all elements in this queue, in descending order.
- *
- * @return list of cached elements in descending order
- */
- private List<org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock>
- getList(final CachedBlockQueue queue) {
- return List.of(queue.get());
- }
-
-}
diff --git
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestLruBlockCache.java
b/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestLruBlockCache.java
deleted file mode 100644
index d5a23c1bd8..0000000000
---
a/core/src/test/java/org/apache/accumulo/core/file/blockfile/cache/TestLruBlockCache.java
+++ /dev/null
@@ -1,552 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.accumulo.core.file.blockfile.cache;
-
-import static org.apache.accumulo.core.util.LazySingletons.RANDOM;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.accumulo.core.conf.ConfigurationCopy;
-import org.apache.accumulo.core.conf.DefaultConfiguration;
-import org.apache.accumulo.core.conf.Property;
-import
org.apache.accumulo.core.file.blockfile.cache.impl.BlockCacheConfiguration;
-import
org.apache.accumulo.core.file.blockfile.cache.impl.BlockCacheManagerFactory;
-import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
-import org.apache.accumulo.core.file.blockfile.cache.lru.CachedBlock;
-import org.apache.accumulo.core.file.blockfile.cache.lru.HeapSize;
-import org.apache.accumulo.core.file.blockfile.cache.lru.LruBlockCache;
-import
org.apache.accumulo.core.file.blockfile.cache.lru.LruBlockCacheConfiguration;
-import org.apache.accumulo.core.file.blockfile.cache.lru.LruBlockCacheManager;
-import org.apache.accumulo.core.spi.cache.BlockCacheManager;
-import org.apache.accumulo.core.spi.cache.CacheEntry;
-import org.apache.accumulo.core.spi.cache.CacheType;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the concurrent LruBlockCache.
- * <p>
- *
- * Tests will ensure it grows and shrinks in size properly, evictions run when
they're supposed to
- * and do what they should, and that cached blocks are accessible when
expected to be.
- */
-@SuppressWarnings("deprecation")
-public class TestLruBlockCache {
-
- @Test
- public void testConfiguration() {
- ConfigurationCopy cc = new ConfigurationCopy();
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(1019));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(1000023));
- cc.set(Property.TSERV_DATACACHE_SIZE, Long.toString(1000027));
- cc.set(Property.TSERV_SUMMARYCACHE_SIZE, Long.toString(1000029));
-
- LruBlockCacheConfiguration.builder(Property.TSERV_PREFIX, CacheType.INDEX)
-
.useEvictionThread(false).minFactor(0.93f).acceptableFactor(0.97f).singleFactor(0.20f)
-
.multiFactor(0.30f).memoryFactor(0.50f).mapConcurrencyLevel(5).buildMap().forEach(cc::set);
-
- String defaultPrefix =
BlockCacheConfiguration.getCachePropertyBase(Property.TSERV_PREFIX)
- + LruBlockCacheConfiguration.PROPERTY_PREFIX + ".default.";
-
- // this should be overridden by cache type specific setting
- cc.set(defaultPrefix + LruBlockCacheConfiguration.MEMORY_FACTOR_PROPERTY,
"0.6");
-
- // this is not set for the cache type, so should fall back to default
- cc.set(defaultPrefix + LruBlockCacheConfiguration.MAP_LOAD_PROPERTY,
"0.53");
-
- BlockCacheConfiguration bcc = BlockCacheConfiguration.forTabletServer(cc);
- LruBlockCacheConfiguration lbcc = new LruBlockCacheConfiguration(bcc,
CacheType.INDEX);
-
- assertFalse(lbcc.isUseEvictionThread());
- assertEquals(0.93f, lbcc.getMinFactor(), 0.0000001);
- assertEquals(0.97f, lbcc.getAcceptableFactor(), 0.0000001);
- assertEquals(0.20f, lbcc.getSingleFactor(), 0.0000001);
- assertEquals(0.30f, lbcc.getMultiFactor(), 0.0000001);
- assertEquals(0.50f, lbcc.getMemoryFactor(), 0.0000001);
- assertEquals(0.53f, lbcc.getMapLoadFactor(), 0.0000001);
- assertEquals(5, lbcc.getMapConcurrencyLevel());
- assertEquals(1019, lbcc.getBlockSize());
- assertEquals(1000023, lbcc.getMaxSize());
- }
-
- @Test
- public void testBackgroundEvictionThread() throws Exception {
-
- long maxSize = 100000;
- long blockSize = calculateBlockSizeDefault(maxSize, 9); // room for 9,
will evict
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] blocks = generateFixedBlocks(10, blockSize, "block");
-
- // Add all the blocks
- for (Block block : blocks) {
- cache.cacheBlock(block.blockName, block.buf);
- }
-
- // Let the eviction run
- int n = 0;
- while (cache.getEvictionCount() == 0) {
- Thread.sleep(1000);
- assertTrue(n++ < 1);
- }
- // A single eviction run should have occurred
- assertEquals(cache.getEvictionCount(), 1);
-
- manager.stop();
- }
-
- @Test
- public void testCacheSimple() throws Exception {
-
- long maxSize = 1000000;
- long blockSize = calculateBlockSizeDefault(maxSize, 101);
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] blocks = generateRandomBlocks(100, blockSize);
-
- long expectedCacheSize = cache.heapSize();
-
- // Confirm empty
- for (Block block : blocks) {
- assertNull(cache.getBlock(block.blockName));
- }
-
- // Add blocks
- for (Block block : blocks) {
- cache.cacheBlock(block.blockName, block.buf);
- expectedCacheSize += block.heapSize();
- }
-
- // Verify correctly calculated cache heap size
- assertEquals(expectedCacheSize, cache.heapSize());
-
- // Check if all blocks are properly cached and retrieved
- for (Block block : blocks) {
- CacheEntry ce = cache.getBlock(block.blockName);
- assertNotNull(ce);
- assertEquals(ce.getBuffer().length, block.buf.length);
- }
-
- // Verify correctly calculated cache heap size
- assertEquals(expectedCacheSize, cache.heapSize());
-
- // Check if all blocks are properly cached and retrieved
- for (Block block : blocks) {
- CacheEntry ce = cache.getBlock(block.blockName);
- assertNotNull(ce);
- assertEquals(ce.getBuffer().length, block.buf.length);
- }
-
- // Expect no evictions
- assertEquals(0, cache.getEvictionCount());
- // Thread t = new LruBlockCache.StatisticsThread(cache);
- // t.start();
- // t.join();
- manager.stop();
- }
-
- @Test
- public void testCacheEvictionSimple() throws Exception {
-
- long maxSize = 100000;
- long blockSize = calculateBlockSizeDefault(maxSize, 10);
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- LruBlockCacheConfiguration.builder(Property.TSERV_PREFIX, CacheType.INDEX)
- .useEvictionThread(false).buildMap().forEach(cc::set);
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
-
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] blocks = generateFixedBlocks(10, blockSize, "block");
-
- long expectedCacheSize = cache.heapSize();
-
- // Add all the blocks
- for (Block block : blocks) {
- cache.cacheBlock(block.blockName, block.buf);
- expectedCacheSize += block.heapSize();
- }
-
- // A single eviction run should have occurred
- assertEquals(1, cache.getEvictionCount());
-
- // Our expected size overruns acceptable limit
- assertTrue(
- expectedCacheSize > (maxSize *
LruBlockCacheConfiguration.DEFAULT_ACCEPTABLE_FACTOR));
-
- // But the cache did not grow beyond max
- assertTrue(cache.heapSize() < maxSize);
-
- // And is still below the acceptable limit
- assertTrue(cache.heapSize() < (maxSize *
LruBlockCacheConfiguration.DEFAULT_ACCEPTABLE_FACTOR));
-
- // All blocks except block 0 and 1 should be in the cache
- assertNull(cache.getBlock(blocks[0].blockName));
- assertNull(cache.getBlock(blocks[1].blockName));
- for (int i = 2; i < blocks.length; i++) {
- assertArrayEquals(cache.getBlock(blocks[i].blockName).getBuffer(),
blocks[i].buf);
- }
- manager.stop();
- }
-
- @Test
- public void testCacheEvictionTwoPriorities() throws Exception {
-
- long maxSize = 100000;
- long blockSize = calculateBlockSizeDefault(maxSize, 10);
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- LruBlockCacheConfiguration.builder(Property.TSERV_PREFIX, CacheType.INDEX)
-
.useEvictionThread(false).minFactor(0.98f).acceptableFactor(0.99f).singleFactor(0.25f)
- .multiFactor(0.50f).memoryFactor(0.25f).buildMap().forEach(cc::set);
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] singleBlocks = generateFixedBlocks(5, 10000, "single");
- Block[] multiBlocks = generateFixedBlocks(5, 10000, "multi");
-
- long expectedCacheSize = cache.heapSize();
-
- // Add and get the multi blocks
- for (Block block : multiBlocks) {
- cache.cacheBlock(block.blockName, block.buf);
- expectedCacheSize += block.heapSize();
- assertArrayEquals(cache.getBlock(block.blockName).getBuffer(),
block.buf);
- }
-
- // Add the single blocks (no get)
- for (Block block : singleBlocks) {
- cache.cacheBlock(block.blockName, block.buf);
- expectedCacheSize += block.heapSize();
- }
-
- // A single eviction run should have occurred
- assertEquals(cache.getEvictionCount(), 1);
-
- // We expect two entries evicted
- assertEquals(cache.getEvictedCount(), 2);
-
- // Our expected size overruns acceptable limit
- assertTrue(
- expectedCacheSize > (maxSize *
LruBlockCacheConfiguration.DEFAULT_ACCEPTABLE_FACTOR));
-
- // But the cache did not grow beyond max
- assertTrue(cache.heapSize() <= maxSize);
-
- // And is now below the acceptable limit
- assertTrue(
- cache.heapSize() <= (maxSize *
LruBlockCacheConfiguration.DEFAULT_ACCEPTABLE_FACTOR));
-
- // We expect fairness across the two priorities.
- // This test makes multi go barely over its limit, in-memory
- // empty, and the rest in single. Two single evictions and
- // one multi eviction expected.
- assertNull(cache.getBlock(singleBlocks[0].blockName));
- assertNull(cache.getBlock(multiBlocks[0].blockName));
-
- // And all others to be cached
- for (int i = 1; i < 4; i++) {
- assertArrayEquals(cache.getBlock(singleBlocks[i].blockName).getBuffer(),
singleBlocks[i].buf);
- assertArrayEquals(cache.getBlock(multiBlocks[i].blockName).getBuffer(),
multiBlocks[i].buf);
- }
- manager.stop();
- }
-
- @Test
- public void testCacheEvictionThreePriorities() throws Exception {
-
- long maxSize = 100000;
- long blockSize = calculateBlockSize(maxSize, 10);
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- LruBlockCacheConfiguration.builder(Property.TSERV_PREFIX, CacheType.INDEX)
-
.useEvictionThread(false).minFactor(0.98f).acceptableFactor(0.99f).singleFactor(0.33f)
- .multiFactor(0.33f).memoryFactor(0.34f).buildMap().forEach(cc::set);
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] singleBlocks = generateFixedBlocks(5, blockSize, "single");
- Block[] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
- Block[] memoryBlocks = generateFixedBlocks(5, blockSize, "memory");
-
- long expectedCacheSize = cache.heapSize();
-
- // Add 3 blocks from each priority
- for (int i = 0; i < 3; i++) {
-
- // Just add single blocks
- cache.cacheBlock(singleBlocks[i].blockName, singleBlocks[i].buf);
- expectedCacheSize += singleBlocks[i].heapSize();
-
- // Add and get multi blocks
- cache.cacheBlock(multiBlocks[i].blockName, multiBlocks[i].buf);
- expectedCacheSize += multiBlocks[i].heapSize();
- cache.getBlock(multiBlocks[i].blockName);
-
- // Add memory blocks as such
- cache.cacheBlock(memoryBlocks[i].blockName, memoryBlocks[i].buf, true);
- expectedCacheSize += memoryBlocks[i].heapSize();
-
- }
-
- // Do not expect any evictions yet
- assertEquals(0, cache.getEvictionCount());
-
- // Verify cache size
- assertEquals(expectedCacheSize, cache.heapSize());
-
- // Insert a single block, oldest single should be evicted
- cache.cacheBlock(singleBlocks[3].blockName, singleBlocks[3].buf);
-
- // Single eviction, one thing evicted
- assertEquals(1, cache.getEvictionCount());
- assertEquals(1, cache.getEvictedCount());
-
- // Verify oldest single block is the one evicted
- assertNull(cache.getBlock(singleBlocks[0].blockName));
-
- // Change the oldest remaining single block to a multi
- cache.getBlock(singleBlocks[1].blockName);
-
- // Insert another single block
- cache.cacheBlock(singleBlocks[4].blockName, singleBlocks[4].buf);
-
- // Two evictions, two evicted.
- assertEquals(2, cache.getEvictionCount());
- assertEquals(2, cache.getEvictedCount());
-
- // Oldest multi block should be evicted now
- assertNull(cache.getBlock(multiBlocks[0].blockName));
-
- // Insert another memory block
- cache.cacheBlock(memoryBlocks[3].blockName, memoryBlocks[3].buf, true);
-
- // Three evictions, three evicted.
- assertEquals(3, cache.getEvictionCount());
- assertEquals(3, cache.getEvictedCount());
-
- // Oldest memory block should be evicted now
- assertNull(cache.getBlock(memoryBlocks[0].blockName));
-
- // Add a block that is twice as big (should force two evictions)
- Block[] bigBlocks = generateFixedBlocks(3, blockSize * 3, "big");
- cache.cacheBlock(bigBlocks[0].blockName, bigBlocks[0].buf);
-
- // Four evictions, six evicted (inserted block 3X size, expect +3 evicted)
- assertEquals(4, cache.getEvictionCount());
- assertEquals(6, cache.getEvictedCount());
-
- // Expect three remaining singles to be evicted
- assertNull(cache.getBlock(singleBlocks[2].blockName));
- assertNull(cache.getBlock(singleBlocks[3].blockName));
- assertNull(cache.getBlock(singleBlocks[4].blockName));
-
- // Make the big block a multi block
- cache.getBlock(bigBlocks[0].blockName);
-
- // Cache another single big block
- cache.cacheBlock(bigBlocks[1].blockName, bigBlocks[1].buf);
-
- // Five evictions, nine evicted (3 new)
- assertEquals(5, cache.getEvictionCount());
- assertEquals(9, cache.getEvictedCount());
-
- // Expect three remaining multis to be evicted
- assertNull(cache.getBlock(singleBlocks[1].blockName));
- assertNull(cache.getBlock(multiBlocks[1].blockName));
- assertNull(cache.getBlock(multiBlocks[2].blockName));
-
- // Cache a big memory block
- cache.cacheBlock(bigBlocks[2].blockName, bigBlocks[2].buf, true);
-
- // Six evictions, twelve evicted (3 new)
- assertEquals(6, cache.getEvictionCount());
- assertEquals(12, cache.getEvictedCount());
-
- // Expect three remaining in-memory to be evicted
- assertNull(cache.getBlock(memoryBlocks[1].blockName));
- assertNull(cache.getBlock(memoryBlocks[2].blockName));
- assertNull(cache.getBlock(memoryBlocks[3].blockName));
-
- manager.stop();
- }
-
- // test scan resistance
- @Test
- public void testScanResistance() throws Exception {
-
- long maxSize = 100000;
- long blockSize = calculateBlockSize(maxSize, 10);
-
- DefaultConfiguration dc = DefaultConfiguration.getInstance();
- ConfigurationCopy cc = new ConfigurationCopy(dc);
- cc.set(Property.GENERAL_CACHE_MANAGER_IMPL,
LruBlockCacheManager.class.getName());
- BlockCacheManager manager = BlockCacheManagerFactory.getInstance(cc);
- cc.set(Property.TSERV_DEFAULT_BLOCKSIZE, Long.toString(blockSize));
- cc.set(Property.TSERV_INDEXCACHE_SIZE, Long.toString(maxSize));
- LruBlockCacheConfiguration.builder(Property.TSERV_PREFIX, CacheType.INDEX)
-
.useEvictionThread(false).minFactor(0.66f).acceptableFactor(0.99f).singleFactor(0.33f)
- .multiFactor(0.33f).memoryFactor(0.34f).buildMap().forEach(cc::set);
- manager.start(BlockCacheConfiguration.forTabletServer(cc));
- LruBlockCache cache = (LruBlockCache)
manager.getBlockCache(CacheType.INDEX);
-
- Block[] singleBlocks = generateFixedBlocks(20, blockSize, "single");
- Block[] multiBlocks = generateFixedBlocks(5, blockSize, "multi");
-
- // Add 5 multi blocks
- for (Block block : multiBlocks) {
- cache.cacheBlock(block.blockName, block.buf);
- cache.getBlock(block.blockName);
- }
-
- // Add 5 single blocks
- for (int i = 0; i < 5; i++) {
- cache.cacheBlock(singleBlocks[i].blockName, singleBlocks[i].buf);
- }
-
- // An eviction ran
- assertEquals(1, cache.getEvictionCount());
-
- // To drop down to 2/3 capacity, we'll need to evict 4 blocks
- assertEquals(4, cache.getEvictedCount());
-
- // Should have been taken off equally from single and multi
- assertNull(cache.getBlock(singleBlocks[0].blockName));
- assertNull(cache.getBlock(singleBlocks[1].blockName));
- assertNull(cache.getBlock(multiBlocks[0].blockName));
- assertNull(cache.getBlock(multiBlocks[1].blockName));
-
- // Let's keep "scanning" by adding single blocks. From here on we only
- // expect evictions from the single bucket.
-
- // Every time we reach 10 total blocks (every 4 inserts) we get 4 single
- // blocks evicted. Inserting 13 blocks should yield 3 more evictions and
- // 12 more evicted.
-
- for (int i = 5; i < 18; i++) {
- cache.cacheBlock(singleBlocks[i].blockName, singleBlocks[i].buf);
- }
-
- // 4 total evictions, 16 total evicted
- assertEquals(4, cache.getEvictionCount());
- assertEquals(16, cache.getEvictedCount());
-
- // Should now have 7 total blocks
- assertEquals(7, cache.size());
-
- manager.stop();
- }
-
- private Block[] generateFixedBlocks(int numBlocks, int size, String pfx) {
- Block[] blocks = new Block[numBlocks];
- for (int i = 0; i < numBlocks; i++) {
- blocks[i] = new Block(pfx + i, size);
- }
- return blocks;
- }
-
- private Block[] generateFixedBlocks(int numBlocks, long size, String pfx) {
- return generateFixedBlocks(numBlocks, (int) size, pfx);
- }
-
- private Block[] generateRandomBlocks(int numBlocks, long maxSize) {
- Block[] blocks = new Block[numBlocks];
- for (int i = 0; i < numBlocks; i++) {
- blocks[i] = new Block("block" + i, RANDOM.get().nextInt((int) maxSize) +
1);
- }
- return blocks;
- }
-
- private long calculateBlockSize(long maxSize, int numBlocks) {
- long roughBlockSize = maxSize / numBlocks;
- int numEntries = (int) Math.ceil((1.2) * maxSize / roughBlockSize);
- long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
ClassSize.CONCURRENT_HASHMAP
- + ((long) numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY)
- + ((long) LruBlockCacheConfiguration.DEFAULT_CONCURRENCY_LEVEL
- * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
- long negateBlockSize = totalOverhead / numEntries;
- negateBlockSize += CachedBlock.PER_BLOCK_OVERHEAD;
- return ClassSize.align((long) Math.floor((roughBlockSize -
negateBlockSize) * 0.99f));
- }
-
- private long calculateBlockSizeDefault(long maxSize, int numBlocks) {
- long roughBlockSize = maxSize / numBlocks;
- int numEntries = (int) Math.ceil((1.2) * maxSize / roughBlockSize);
- long totalOverhead = LruBlockCache.CACHE_FIXED_OVERHEAD +
ClassSize.CONCURRENT_HASHMAP
- + ((long) numEntries * ClassSize.CONCURRENT_HASHMAP_ENTRY)
- + ((long) LruBlockCacheConfiguration.DEFAULT_CONCURRENCY_LEVEL
- * ClassSize.CONCURRENT_HASHMAP_SEGMENT);
- long negateBlockSize = totalOverhead / numEntries;
- negateBlockSize += CachedBlock.PER_BLOCK_OVERHEAD;
- return ClassSize.align((long) Math.floor(
- (roughBlockSize - negateBlockSize) *
LruBlockCacheConfiguration.DEFAULT_ACCEPTABLE_FACTOR));
- }
-
- private static class Block implements HeapSize {
- String blockName;
- byte[] buf;
-
- Block(String blockName, int size) {
- this.blockName = blockName;
- this.buf = new byte[size];
- }
-
- @Override
- public long heapSize() {
- return CachedBlock.PER_BLOCK_OVERHEAD +
ClassSize.align(blockName.length())
- + ClassSize.align(buf.length);
- }
- }
-}
diff --git
a/hadoop-mapreduce/src/main/java/org/apache/accumulo/hadoopImpl/mapreduce/lib/ConfiguratorBase.java
b/hadoop-mapreduce/src/main/java/org/apache/accumulo/hadoopImpl/mapreduce/lib/ConfiguratorBase.java
index 22a280c13a..2a1cbf370c 100644
---
a/hadoop-mapreduce/src/main/java/org/apache/accumulo/hadoopImpl/mapreduce/lib/ConfiguratorBase.java
+++
b/hadoop-mapreduce/src/main/java/org/apache/accumulo/hadoopImpl/mapreduce/lib/ConfiguratorBase.java
@@ -161,7 +161,7 @@ public class ConfiguratorBase {
* Sets the valid visibility count for this job.
*
* @param conf the Hadoop configuration object to configure
- * @param visibilityCacheSize the LRU cache size
+ * @param visibilityCacheSize the cache size
*/
public static void setVisibilityCacheSize(Configuration conf, int
visibilityCacheSize) {
conf.setInt(enumToConfKey(GeneralOpts.VISIBILITY_CACHE_SIZE),
visibilityCacheSize);