org.glassfish.hk2.utilities.cache.LRUHybridCache Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) 2013, 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.hk2.utilities.cache;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
/**
* Hybrid cache that allows explicit removals of included entries as well
* as implicit removal of entries that have been least recently accessed.
* The implicit removal happens only in case the internal cache runs out of space.
* Maximum number of items that can be kept in the cache is invariant for a single cache instance,
* and can be set in the cache constructor. The cache deals with {@link HybridCacheEntry}
* items than could even instruct the cache to drop them as they get computed.
* The cache will still make sure such items get computed just once in given time (based on computation length)
* for given key.
*
* Desired value will only be computed once and computed value stored in the cache.
* The implementation is based on an example from the "Java Concurrency in Practice" book
* authored by Brian Goetz and company.
*
* @author Jakub Podlesak (jakub.podlesak at oracle.com)
* @param The type for the keys in the cache
* @param The type for the values in the cache
*/
public class LRUHybridCache implements Computable> {
/**
* Should a cycle be detected during computation of a value
* for given key, this interface allows client code to register
* a callback that would get invoked in such a case.
*
* The cycle is defined as follows. If any thread starts computation
* for given key and code from the very same thread requests the computed value
* before the computation ends, a cycle is detected.
* Registered cycle handler is then given a chance to handle the cycle and
* throw a runtime exception if appropriate.
*
* @param Key type.
*/
public interface CycleHandler {
/**
* Handle cycle that was detected while computing a cache value
* for given key. This method would typically just throw a runtime exception.
*
* @param key instance that caused the cycle.
*/
public void handleCycle(K key);
}
private final LRUHybridCache.CycleHandler cycleHandler;
/**
* Helper class, that remembers the future task origin thread, so that cycles could be detected.
*/
private class OriginThreadAwareFuture implements Future> {
private final K key;
private final FutureTask> future;
private volatile long threadId;
private volatile long lastHit;
OriginThreadAwareFuture(LRUHybridCache> cache, final K key) {
this.key = key;
this.threadId = Thread.currentThread().getId();
Callable> eval = new Callable>() {
@Override
public HybridCacheEntry call() throws Exception {
try {
final HybridCacheEntry result = computable.compute(key);
return result;
} finally {
threadId = -1;
}
}
};
this.future = new FutureTask>(eval);
this.lastHit = System.nanoTime();
}
@Override
public int hashCode() {
return future.hashCode();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final LRUHybridCache.OriginThreadAwareFuture other = (LRUHybridCache.OriginThreadAwareFuture) obj;
if (this.future != other.future && (this.future == null || !this.future.equals(other.future))) {
return false;
}
return true;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return future.isCancelled();
}
@Override
public boolean isDone() {
return future.isDone();
}
@Override
public HybridCacheEntry get() throws InterruptedException, ExecutionException {
return future.get();
}
@Override
public HybridCacheEntry get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
public void run() {
future.run();
}
}
private static final LRUHybridCache.CycleHandler