下面列出了com.google.common.util.concurrent.ExecutionError#com.google.common.cache.CacheLoader.InvalidCacheLoadException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference)
throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue)
throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
private static Optional<Money> getPremiumPriceFromList(String label, PremiumList premiumList) {
// Consult the bloom filter and immediately return if the label definitely isn't premium.
if (!premiumList.getBloomFilter().mightContain(label)) {
return Optional.empty();
}
RevisionIdAndLabel revisionIdAndLabel =
RevisionIdAndLabel.create(premiumList.getRevisionId(), label);
try {
Optional<BigDecimal> price = PremiumListCache.cachePremiumEntries.get(revisionIdAndLabel);
return price.map(
p ->
Money.of(
premiumList.getCurrency(),
p.setScale(premiumList.getCurrency().getDecimalPlaces())));
} catch (InvalidCacheLoadException | ExecutionException e) {
throw new RuntimeException(
String.format(
"Could not load premium entry %s for list %s",
revisionIdAndLabel, premiumList.getName()),
e);
}
}
public void testBulkLoad_partial() throws ExecutionException {
final Object extraKey = new Object();
final Object extraValue = new Object();
CacheLoader<Object, Object> loader = new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) {
throw new AssertionError();
}
@Override
public Map<Object, Object> loadAll(Iterable<? extends Object> keys) {
Map<Object, Object> result = Maps.newHashMap();
// ignore request keys
result.put(extraKey, extraValue);
return result;
}
};
LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder(), loader);
Object[] lookupKeys = new Object[] { new Object(), new Object(), new Object() };
try {
cache.getAll(asList(lookupKeys));
fail();
} catch (InvalidCacheLoadException expected) {}
assertSame(extraValue, cache.asMap().get(extraKey));
}
public void testBulkLoadNull() throws ExecutionException {
LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
.recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(constantLoader(null)));
CacheStats stats = cache.stats();
assertEquals(0, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(0, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
try {
cache.getAll(asList(new Object()));
fail();
} catch (InvalidCacheLoadException expected) {}
stats = cache.stats();
assertEquals(1, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(1, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
}
private static CheckResults checkStatus(PremiumListRevision premiumListRevision, String label) {
if (!premiumListRevision.getProbablePremiumLabels().mightContain(label)) {
return CheckResults.create(BLOOM_FILTER_NEGATIVE, Optional.empty());
}
Key<PremiumListEntry> entryKey =
Key.create(Key.create(premiumListRevision), PremiumListEntry.class, label);
try {
// getIfPresent() returns null if the key is not in the cache
Optional<PremiumListEntry> entry = cachePremiumListEntries.getIfPresent(entryKey);
if (entry != null) {
if (entry.isPresent()) {
return CheckResults.create(CACHED_POSITIVE, Optional.of(entry.get().getValue()));
} else {
return CheckResults.create(CACHED_NEGATIVE, Optional.empty());
}
}
entry = cachePremiumListEntries.get(entryKey);
if (entry.isPresent()) {
return CheckResults.create(UNCACHED_POSITIVE, Optional.of(entry.get().getValue()));
} else {
return CheckResults.create(UNCACHED_NEGATIVE, Optional.empty());
}
} catch (InvalidCacheLoadException | ExecutionException e) {
throw new RuntimeException("Could not load premium list entry " + entryKey, e);
}
}
public void testBulkLoadNullMap() throws ExecutionException {
LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
.recordStats(), new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) {
throw new AssertionError();
}
@Override
public Map<Object, Object> loadAll(Iterable<? extends Object> keys) {
return null;
}
});
CacheStats stats = cache.stats();
assertEquals(0, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(0, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
try {
cache.getAll(asList(new Object()));
fail();
} catch (InvalidCacheLoadException expected) {}
stats = cache.stats();
assertEquals(1, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(1, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
}
/**
* On a concurrent computation that returns null, all threads should get an
* InvalidCacheLoadException, with the loader only called once. The result should not be cached
* (a later request should call the loader again).
*/
private static void testConcurrentLoadingNull(Caffeine<Object, Object> builder)
throws InterruptedException {
int count = 10;
final AtomicInteger callCount = new AtomicInteger();
final CountDownLatch startSignal = new CountDownLatch(count + 1);
LoadingCache<String, String> cache = CaffeinatedGuava.build(builder,
new CacheLoader<String, String>() {
@Override public String load(String key) {
callCount.incrementAndGet();
assertTrue(Uninterruptibles.awaitUninterruptibly(startSignal, 300, TimeUnit.SECONDS));
return null;
}
});
List<Object> result = doConcurrentGet(cache, "bar", count, startSignal);
assertEquals(count, callCount.get());
for (int i = 0; i < count; i++) {
assertTrue(result.get(i) instanceof InvalidCacheLoadException);
}
// subsequent calls should call the loader again, not get the old exception
try {
cache.getUnchecked("bar");
fail();
} catch (InvalidCacheLoadException expected) {
}
assertEquals(count + 1, callCount.get());
}
public void testGet_computeNull() {
LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
.maximumSize(0)
.removalListener(listener),
constantLoader(null));
try {
cache.getUnchecked(new Object());
fail();
} catch (InvalidCacheLoadException e) { /* expected */}
assertTrue(listener.isEmpty());
checkEmpty(cache);
}
/**
* Returns the premium price for the specified label and registry, or absent if the label is not
* premium.
*/
public static Optional<Money> getPremiumPrice(String label, Registry registry) {
// If the registry has no configured premium list, then no labels are premium.
if (registry.getPremiumList() == null) {
return Optional.empty();
}
DateTime startTime = DateTime.now(UTC);
String listName = registry.getPremiumList().getName();
Optional<PremiumList> optionalPremiumList = PremiumList.getCached(listName);
checkState(optionalPremiumList.isPresent(), "Could not load premium list '%s'", listName);
PremiumList premiumList = optionalPremiumList.get();
PremiumListRevision revision;
try {
revision = cachePremiumListRevisions.get(premiumList.getRevisionKey());
} catch (InvalidCacheLoadException | ExecutionException e) {
throw new RuntimeException(
"Could not load premium list revision " + premiumList.getRevisionKey(), e);
}
checkState(
revision.getProbablePremiumLabels() != null,
"Probable premium labels Bloom filter is null on revision '%s'",
premiumList.getRevisionKey());
CheckResults checkResults = checkStatus(revision, label);
DomainLabelMetrics.recordPremiumListCheckOutcome(
registry.getTldStr(),
listName,
checkResults.checkOutcome(),
DateTime.now(UTC).getMillis() - startTime.getMillis());
// Also load the value from Cloud SQL, compare the two results, and log if different.
try {
Optional<Money> priceFromSql = PremiumListDao.getPremiumPrice(label, registry);
if (!priceFromSql.equals(checkResults.premiumPrice())) {
logger.atWarning().log(
"Unequal prices for domain %s.%s from Datastore (%s) and Cloud SQL (%s).",
label, registry.getTldStr(), checkResults.premiumPrice(), priceFromSql);
}
} catch (Throwable t) {
logger.atSevere().withCause(t).log(
"Error loading price of domain %s.%s from Cloud SQL.", label, registry.getTldStr());
}
return checkResults.premiumPrice();
}
@Override
public Element getElement(final Object id) throws IllegalStateException {
try {
// if (isProxied()) {
// System.out.println("Getting a proxied element for id: " + String.valueOf(id));
// }
NoteCoordinate nc = normalizeId((Serializable) id);
Element result = null;
// if (nc.getReplicaId().equalsIgnoreCase("852582F7007073B5")) {
// System.out.println("Getting a demo document " + nc + " from the element cache");
// result = getElementCache().get(nc);
// if (result != null) {
// System.out.println(
// "Result was loaded from cache with id " + nc + " and cache now has " + getElementCache().size() + " elements");
//
// }
// } else {
result = getElementCache().get(nc);
// }
// if (isProxied()) {
// if (result instanceof DProxyVertex) {
// NoteCoordinate proxyid = ((DProxyVertex) result).getProxiedId();
// getElementCache().put(proxyid, result);
// }
// }
// System.out.println("TEMP DEBUG requesting element for id " + id.getClass().getSimpleName() + ": " + String.valueOf(id)
// + " from element store " + System.identityHashCode(this) + " using element cache "
// + System.identityHashCode(getElementCache()) + " resulting in a " + result.getClass().getSimpleName() + ": "
// + System.identityHashCode(result));
return result;
} catch (InvalidCacheLoadException icle) {
// System.out.println(
// "TEMP DEBUG invalidCacheLoad for id " + String.valueOf(id) + " from element store " + System.identityHashCode(this));
return null;
} catch (UncheckedExecutionException uee) {
Throwable cause = uee.getCause();
if (cause != null && cause instanceof UserAccessException) {
throw new UserAccessException(cause.getMessage(), cause);
} else {
throw uee;
}
} catch (UserAccessException uae) {
throw uae;
} catch (Throwable t) {
throw new IllegalStateException("Unable to retrieve id " + String.valueOf(id), t);
}
}
public <F> F getElement(final Object id, final Class<F> kind) {
F result = null;
if (id == null) {
return null;
}
try {
// System.out.println("Attempting to retrieve a " + (null == kind ? "Frame" : kind.getName()) + " with id "
// + (null == id ? "null" : String.valueOf(id)));
Object cacheChk = getFramedElementCache().get(id, new FrameLoadCallable(this, id, kind, Element.class));
if (cacheChk != null && (kind == null || kind.isAssignableFrom(cacheChk.getClass()))) {
if (cacheChk instanceof VertexFrame) {
Vertex v = ((VertexFrame) cacheChk).asVertex();
if (v instanceof DProxyVertex) {
NoteCoordinate proxyid = ((DProxyVertex) v).getProxiedId();
if (proxyid != null) {
getFramedElementCache().put(proxyid, cacheChk);
}
}
}
return (F) cacheChk;
}
} catch (InvalidCacheLoadException icle) {
// System.out.println("Cache miss on id " + String.valueOf(id) + " for type " + (kind == null ? "null" : kind.getName()));
//NTF this is no problem and quite normal
return null;
} catch (UncheckedExecutionException uee) {
Throwable cause = uee.getCause();
if (cause != null && cause instanceof UserAccessException) {
throw new UserAccessException(cause.getMessage(), cause);
} else {
throw uee;
}
} catch (Throwable t) {
t.printStackTrace();
try {
throw t;
} catch (Throwable e) {
e.printStackTrace();
}
}
return result;
}