Search in sources :

Example 81 with UncheckedExecutionException

use of com.google.common.util.concurrent.UncheckedExecutionException in project guava by hceylan.

the class LocalCache method loadAll.

/**
 * Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't
 * implement {@code loadAll}.
 */
@Nullable
Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader) throws ExecutionException {
    Stopwatch stopwatch = new Stopwatch().start();
    Map<K, V> result;
    boolean success = false;
    try {
        // safe since all keys extend K
        @SuppressWarnings("unchecked") Map<K, V> map = (Map<K, V>) loader.loadAll(keys);
        result = map;
        success = true;
    } catch (UnsupportedLoadingOperationException e) {
        success = true;
        throw e;
    } catch (RuntimeException e) {
        throw new UncheckedExecutionException(e);
    } catch (Exception e) {
        throw new ExecutionException(e);
    } catch (Error e) {
        throw new ExecutionError(e);
    } finally {
        if (!success) {
            globalStatsCounter.recordLoadException(stopwatch.elapsedTime(NANOSECONDS));
        }
    }
    if (result == null) {
        globalStatsCounter.recordLoadException(stopwatch.elapsedTime(NANOSECONDS));
        throw new InvalidCacheLoadException(loader + " returned null map from loadAll");
    }
    stopwatch.stop();
    // TODO(fry): batch by segment
    boolean nullsPresent = false;
    for (Map.Entry<K, V> entry : result.entrySet()) {
        K key = entry.getKey();
        V value = entry.getValue();
        if (key == null || value == null) {
            // delay failure until non-null entries are stored
            nullsPresent = true;
        } else {
            put(key, value);
        }
    }
    if (nullsPresent) {
        globalStatsCounter.recordLoadException(stopwatch.elapsedTime(NANOSECONDS));
        throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll");
    }
    // TODO(fry): record count of loaded entries
    globalStatsCounter.recordLoadSuccess(stopwatch.elapsedTime(NANOSECONDS));
    return result;
}
Also used : ExecutionError(com.google.common.util.concurrent.ExecutionError) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Stopwatch(com.google.common.base.Stopwatch) ExecutionError(com.google.common.util.concurrent.ExecutionError) UnsupportedLoadingOperationException(com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException) InvalidCacheLoadException(com.google.common.cache.CacheLoader.InvalidCacheLoadException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InvalidCacheLoadException(com.google.common.cache.CacheLoader.InvalidCacheLoadException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) AbstractMap(java.util.AbstractMap) UnsupportedLoadingOperationException(com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException) Nullable(javax.annotation.Nullable)

Example 82 with UncheckedExecutionException

use of com.google.common.util.concurrent.UncheckedExecutionException in project guava by google.

the class LocalCache method load.

// timestamps as numeric primitives
@SuppressWarnings("GoodTime")
private V load(Object key) throws ExecutionException {
    long startTime = ticker.read();
    V calculatedValue;
    try {
        /*
       * This cast isn't safe, but we can rely on the fact that K is almost always passed to
       * Map.get(), and tools like IDEs and Findbugs can catch situations where this isn't the
       * case.
       *
       * The alternative is to add an overloaded method, but the chances of a user calling get()
       * instead of the new API and the risks inherent in adding a new API outweigh this little
       * hole.
       */
        K castKey = (K) key;
        calculatedValue = loader.load(castKey);
        put(castKey, calculatedValue);
    } catch (RuntimeException e) {
        statsCounter.recordLoadException(ticker.read() - startTime);
        throw new UncheckedExecutionException(e);
    } catch (Exception e) {
        statsCounter.recordLoadException(ticker.read() - startTime);
        throw new ExecutionException(e);
    } catch (Error e) {
        statsCounter.recordLoadException(ticker.read() - startTime);
        throw new ExecutionError(e);
    }
    if (calculatedValue == null) {
        String message = loader + " returned null for key " + key + ".";
        throw new CacheLoader.InvalidCacheLoadException(message);
    }
    statsCounter.recordLoadSuccess(ticker.read() - startTime);
    return calculatedValue;
}
Also used : ExecutionError(com.google.common.util.concurrent.ExecutionError) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionError(com.google.common.util.concurrent.ExecutionError) ExecutionException(java.util.concurrent.ExecutionException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) NoSuchElementException(java.util.NoSuchElementException)

Example 83 with UncheckedExecutionException

use of com.google.common.util.concurrent.UncheckedExecutionException in project guava by google.

the class CacheLoadingTest method testLoadUncheckedException.

public void testLoadUncheckedException() throws ExecutionException {
    Exception e = new RuntimeException();
    CacheLoader<Object, Object> loader = exceptionLoader(e);
    LoadingCache<Object, Object> cache = CacheBuilder.newBuilder().recordStats().build(loader);
    CacheStats stats = cache.stats();
    assertEquals(0, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(0, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
    try {
        cache.get(new Object());
        fail();
    } catch (UncheckedExecutionException expected) {
        assertThat(expected).hasCauseThat().isSameInstanceAs(e);
    }
    stats = cache.stats();
    assertEquals(1, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(1, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
    try {
        cache.getUnchecked(new Object());
        fail();
    } catch (UncheckedExecutionException expected) {
        assertThat(expected).hasCauseThat().isSameInstanceAs(e);
    }
    stats = cache.stats();
    assertEquals(2, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(2, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
    cache.refresh(new Object());
    checkLoggedCause(e);
    stats = cache.stats();
    assertEquals(2, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(3, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
    Exception callableException = new RuntimeException();
    try {
        cache.get(new Object(), throwing(callableException));
        fail();
    } catch (UncheckedExecutionException expected) {
        assertThat(expected).hasCauseThat().isSameInstanceAs(callableException);
    }
    stats = cache.stats();
    assertEquals(3, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(4, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
    try {
        cache.getAll(asList(new Object()));
        fail();
    } catch (UncheckedExecutionException expected) {
        assertThat(expected).hasCauseThat().isSameInstanceAs(e);
    }
    stats = cache.stats();
    assertEquals(4, stats.missCount());
    assertEquals(0, stats.loadSuccessCount());
    assertEquals(5, stats.loadExceptionCount());
    assertEquals(0, stats.hitCount());
}
Also used : UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) IOException(java.io.IOException) InvalidCacheLoadException(com.google.common.cache.CacheLoader.InvalidCacheLoadException) ExecutionException(java.util.concurrent.ExecutionException)

Example 84 with UncheckedExecutionException

use of com.google.common.util.concurrent.UncheckedExecutionException in project guava by google.

the class CacheLoadingTest method testConcurrentLoadingCheckedException.

/**
 * On a concurrent computation that throws a checked exception, all threads should get the
 * (wrapped) exception, with the loader called only once. The result should not be cached (a later
 * request should call the loader again).
 */
private static void testConcurrentLoadingCheckedException(CacheBuilder<Object, Object> builder) throws InterruptedException {
    int count = 10;
    final AtomicInteger callCount = new AtomicInteger();
    final CountDownLatch startSignal = new CountDownLatch(count + 1);
    final IOException e = new IOException();
    LoadingCache<String, String> cache = builder.build(new CacheLoader<String, String>() {

        @Override
        public String load(String key) throws IOException, InterruptedException {
            callCount.incrementAndGet();
            startSignal.await();
            throw e;
        }
    });
    List<Object> result = doConcurrentGet(cache, "bar", count, startSignal);
    assertEquals(1, callCount.get());
    for (int i = 0; i < count; i++) {
        // doConcurrentGet alternates between calling getUnchecked and calling get. If we call get(),
        // we should get an ExecutionException; if we call getUnchecked(), we should get an
        // UncheckedExecutionException.
        int mod = i % 3;
        if (mod == 0 || mod == 2) {
            assertThat(result.get(i)).isInstanceOf(ExecutionException.class);
            assertThat((ExecutionException) result.get(i)).hasCauseThat().isSameInstanceAs(e);
        } else {
            assertThat(result.get(i)).isInstanceOf(UncheckedExecutionException.class);
            assertThat((UncheckedExecutionException) result.get(i)).hasCauseThat().isSameInstanceAs(e);
        }
    }
    // subsequent calls should call the loader again, not get the old exception
    try {
        cache.getUnchecked("bar");
        fail();
    } catch (UncheckedExecutionException expected) {
    }
    assertEquals(2, callCount.get());
}
Also used : UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 85 with UncheckedExecutionException

use of com.google.common.util.concurrent.UncheckedExecutionException in project guava by google.

the class CacheLoadingTest method testConcurrentLoadingUncheckedException.

/**
 * On a concurrent computation that throws an unchecked exception, all threads should get the
 * (wrapped) exception, with the loader called only once. The result should not be cached (a later
 * request should call the loader again).
 */
private static void testConcurrentLoadingUncheckedException(CacheBuilder<Object, Object> builder) throws InterruptedException {
    int count = 10;
    final AtomicInteger callCount = new AtomicInteger();
    final CountDownLatch startSignal = new CountDownLatch(count + 1);
    final RuntimeException e = new RuntimeException();
    LoadingCache<String, String> cache = builder.build(new CacheLoader<String, String>() {

        @Override
        public String load(String key) throws InterruptedException {
            callCount.incrementAndGet();
            startSignal.await();
            throw e;
        }
    });
    List<Object> result = doConcurrentGet(cache, "bar", count, startSignal);
    assertEquals(1, callCount.get());
    for (int i = 0; i < count; i++) {
        // doConcurrentGet alternates between calling getUnchecked and calling get, but an unchecked
        // exception thrown by the loader is always wrapped as an UncheckedExecutionException.
        assertThat(result.get(i)).isInstanceOf(UncheckedExecutionException.class);
        assertThat(((UncheckedExecutionException) result.get(i))).hasCauseThat().isSameInstanceAs(e);
    }
    // subsequent calls should call the loader again, not get the old exception
    try {
        cache.getUnchecked("bar");
        fail();
    } catch (UncheckedExecutionException expected) {
    }
    assertEquals(2, callCount.get());
}
Also used : UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)101 ExecutionException (java.util.concurrent.ExecutionException)60 IOException (java.io.IOException)31 InvalidCacheLoadException (com.google.common.cache.CacheLoader.InvalidCacheLoadException)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)10 Test (org.junit.Test)9 Map (java.util.Map)8 ArrayList (java.util.ArrayList)7 File (java.io.File)6 TimeoutException (java.util.concurrent.TimeoutException)6 Stopwatch (com.google.common.base.Stopwatch)5 ImmutableMap (com.google.common.collect.ImmutableMap)5 HashMap (java.util.HashMap)5 List (java.util.List)5 NoSuchElementException (java.util.NoSuchElementException)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 InputStream (java.io.InputStream)4 Callable (java.util.concurrent.Callable)4 SirixIOException (org.sirix.exception.SirixIOException)4 TypeSignature (com.facebook.presto.common.type.TypeSignature)3