Search in sources :

Example 6 with CompletionException

use of java.util.concurrent.CompletionException in project caffeine by ben-manes.

the class LoadingCacheTest method asyncReload_exception.

@Test
public void asyncReload_exception() throws Exception {
    for (Exception e : Arrays.asList(new Exception(), new RuntimeException())) {
        CacheLoader<Integer, Integer> loader = key -> {
            throw e;
        };
        try {
            loader.asyncReload(1, 1, Runnable::run).join();
            Assert.fail();
        } catch (CompletionException ex) {
            assertThat(ex.getCause(), is(sameInstance(e)));
        }
    }
}
Also used : Arrays(java.util.Arrays) CacheContext(com.github.benmanes.caffeine.cache.testing.CacheContext) Iterables(com.google.common.collect.Iterables) Listeners(org.testng.annotations.Listeners) CacheExecutor(com.github.benmanes.caffeine.cache.testing.CacheSpec.CacheExecutor) HasStats.hasLoadFailureCount(com.github.benmanes.caffeine.cache.testing.HasStats.hasLoadFailureCount) Population(com.github.benmanes.caffeine.cache.testing.CacheSpec.Population) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.testng.annotations.Test) Loader(com.github.benmanes.caffeine.cache.testing.CacheSpec.Loader) CacheSpec(com.github.benmanes.caffeine.cache.testing.CacheSpec) CacheValidationListener(com.github.benmanes.caffeine.cache.testing.CacheValidationListener) ImmutableList(com.google.common.collect.ImmutableList) HasStats.hasLoadSuccessCount(com.github.benmanes.caffeine.cache.testing.HasStats.hasLoadSuccessCount) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Map(java.util.Map) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CheckNoWriter(com.github.benmanes.caffeine.cache.testing.CheckNoWriter) HasStats.hasHitCount(com.github.benmanes.caffeine.cache.testing.HasStats.hasHitCount) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) HasRemovalNotifications.hasRemovalNotifications(com.github.benmanes.caffeine.cache.testing.HasRemovalNotifications.hasRemovalNotifications) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) HasStats.hasMissCount(com.github.benmanes.caffeine.cache.testing.HasStats.hasMissCount) Implementation(com.github.benmanes.caffeine.cache.testing.CacheSpec.Implementation) Ints(com.google.common.primitives.Ints) RemovalNotification(com.github.benmanes.caffeine.cache.testing.RemovalNotification) Matchers.both(org.hamcrest.Matchers.both) ExecutionException(java.util.concurrent.ExecutionException) Listener(com.github.benmanes.caffeine.cache.testing.CacheSpec.Listener) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Compute(com.github.benmanes.caffeine.cache.testing.CacheSpec.Compute) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) Matchers.equalTo(org.hamcrest.Matchers.equalTo) CacheProvider(com.github.benmanes.caffeine.cache.testing.CacheProvider) Matchers.is(org.hamcrest.Matchers.is) Awaits.await(com.github.benmanes.caffeine.testing.Awaits.await) Assert(org.junit.Assert) Collections(java.util.Collections) CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 7 with CompletionException

use of java.util.concurrent.CompletionException in project caffeine by ben-manes.

the class LoadingCacheTest method asyncLoadAll_exception.

@Test
public void asyncLoadAll_exception() throws Exception {
    Exception e = new Exception();
    CacheLoader<Integer, Integer> loader = new CacheLoader<Integer, Integer>() {

        @Override
        public Integer load(Integer key) throws Exception {
            throw new AssertionError();
        }

        @Override
        public Map<Integer, Integer> loadAll(Iterable<? extends Integer> keys) throws Exception {
            throw e;
        }
    };
    try {
        loader.asyncLoadAll(Arrays.asList(1), Runnable::run).join();
    } catch (CompletionException ex) {
        assertThat(ex.getCause(), is(sameInstance(e)));
    }
}
Also used : CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 8 with CompletionException

use of java.util.concurrent.CompletionException in project caffeine by ben-manes.

the class CacheLoader method asyncLoadAll.

/**
   * Asynchronously computes or retrieves the values corresponding to {@code keys}. This method is
   * called by {@link AsyncLoadingCache#getAll}.
   * <p>
   * If the returned map doesn't contain all requested {@code keys} then the entries it does contain
   * will be cached and {@code getAll} will return the partial results. If the returned map contains
   * extra keys not present in {@code keys} then all returned entries will be cached, but only the
   * entries for {@code keys} will be returned from {@code getAll}.
   * <p>
   * This method should be overridden when bulk retrieval is significantly more efficient than many
   * individual lookups. Note that {@link AsyncLoadingCache#getAll} will defer to individual calls
   * to {@link AsyncLoadingCache#get} if this method is not overridden.
   *
   * @param keys the unique, non-null keys whose values should be loaded
   * @param executor the executor that with asynchronously loads the entries
   * @return a future containing the map from each key in {@code keys} to the value associated with
   *         that key; <b>may not contain null values</b>
   */
@Override
@Nonnull
default default CompletableFuture<Map<K, V>> asyncLoadAll(@Nonnull Iterable<? extends K> keys, @Nonnull Executor executor) {
    requireNonNull(keys);
    requireNonNull(executor);
    return CompletableFuture.supplyAsync(() -> {
        try {
            return loadAll(keys);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new CompletionException(e);
        }
    }, executor);
}
Also used : CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) Nonnull(javax.annotation.Nonnull)

Example 9 with CompletionException

use of java.util.concurrent.CompletionException in project caffeine by ben-manes.

the class CacheLoader method asyncReload.

/**
   * Asynchronously computes or retrieves a replacement value corresponding to an already-cached
   * {@code key}. If the replacement value is not found then the mapping will be removed if
   * {@code null} is computed. This method is called when an existing cache entry is refreshed by
   * {@link Caffeine#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
   * <p>
   * <b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
   *
   * @param key the non-null key whose value should be loaded
   * @param oldValue the non-null old value corresponding to {@code key}
   * @param executor the executor with which the entry is asynchronously loaded
   * @return a future containing the new value associated with {@code key}, or containing
   *         {@code null} if the mapping is to be removed
   */
@Override
@Nonnull
default default CompletableFuture<V> asyncReload(@Nonnull K key, @Nonnull V oldValue, @Nonnull Executor executor) {
    requireNonNull(key);
    requireNonNull(executor);
    return CompletableFuture.supplyAsync(() -> {
        try {
            return reload(key, oldValue);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new CompletionException(e);
        }
    }, executor);
}
Also used : CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) Nonnull(javax.annotation.Nonnull)

Example 10 with CompletionException

use of java.util.concurrent.CompletionException in project es6draft by anba.

the class AtomicsTestFunctions method evalInWorker.

/**
     * shell-function: {@code evalInWorker(sourceString)}
     * 
     * @param cx
     *            the execution context
     * @param caller
     *            the caller execution context
     * @param sourceString
     *            the script source code
     * @return {@code true} if a new script worker was started, otherwise returns {@code false}
     */
@Function(name = "evalInWorker", arity = 1)
public boolean evalInWorker(ExecutionContext cx, ExecutionContext caller, String sourceString) {
    Source baseSource = Objects.requireNonNull(cx.getRealm().sourceInfo(caller));
    try {
        // TODO: Initialize extensions (console.jsm, window timers?).
        CompletableFuture.supplyAsync(() -> {
            // Set 'executor' to null so it doesn't get shared with the current runtime context.
            /* @formatter:off */
            RuntimeContext context = new RuntimeContext.Builder(cx.getRuntimeContext()).setExecutor(null).build();
            /* @formatter:on */
            World world = new World(context);
            Realm realm;
            try {
                realm = world.newInitializedRealm();
            } catch (IOException | URISyntaxException e) {
                throw new CompletionException(e);
            }
            // Bind test functions to this instance.
            realm.createGlobalProperties(this, AtomicsTestFunctions.class);
            // TODO: Add proper abstraction.
            ModuleLoader moduleLoader = world.getModuleLoader();
            if (moduleLoader instanceof NodeModuleLoader) {
                try {
                    ((NodeModuleLoader) moduleLoader).initialize(realm);
                } catch (IOException | URISyntaxException | MalformedNameException | ResolutionException e) {
                    throw new CompletionException(e);
                }
            }
            // Evaluate the script source code and then run pending jobs.
            Source source = new Source(baseSource, "evalInWorker-script", 1);
            Script script = realm.getScriptLoader().script(source, sourceString);
            Object result = script.evaluate(realm);
            world.runEventLoop();
            return result;
        }, cx.getRuntimeContext().getWorkerExecutor()).whenComplete((r, e) -> {
            if (e instanceof CompletionException) {
                Throwable cause = ((CompletionException) e).getCause();
                cx.getRuntimeContext().getWorkerErrorReporter().accept(cx, (cause != null ? cause : e));
            } else if (e != null) {
                cx.getRuntimeContext().getWorkerErrorReporter().accept(cx, e);
            }
        });
        return true;
    } catch (RejectedExecutionException e) {
        return false;
    }
}
Also used : Script(com.github.anba.es6draft.Script) ModuleLoader(com.github.anba.es6draft.runtime.modules.ModuleLoader) NodeModuleLoader(com.github.anba.es6draft.repl.loader.NodeModuleLoader) NodeModuleLoader(com.github.anba.es6draft.repl.loader.NodeModuleLoader) World(com.github.anba.es6draft.runtime.World) Source(com.github.anba.es6draft.runtime.internal.Source) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CompletionException(java.util.concurrent.CompletionException) SharedArrayBufferObject(com.github.anba.es6draft.runtime.objects.atomics.SharedArrayBufferObject) RuntimeContext(com.github.anba.es6draft.runtime.internal.RuntimeContext) Realm(com.github.anba.es6draft.runtime.Realm) Function(com.github.anba.es6draft.runtime.internal.Properties.Function)

Aggregations

CompletionException (java.util.concurrent.CompletionException)199 Test (org.junit.Test)80 CompletableFuture (java.util.concurrent.CompletableFuture)62 List (java.util.List)52 ArrayList (java.util.ArrayList)51 IOException (java.io.IOException)45 Map (java.util.Map)39 Collection (java.util.Collection)31 ExecutionException (java.util.concurrent.ExecutionException)31 HashMap (java.util.HashMap)30 Collections (java.util.Collections)24 TimeUnit (java.util.concurrent.TimeUnit)22 Collectors (java.util.stream.Collectors)22 FlinkException (org.apache.flink.util.FlinkException)22 Before (org.junit.Before)21 Duration (java.time.Duration)19 Arrays (java.util.Arrays)19 BeforeClass (org.junit.BeforeClass)19 ExecutorService (java.util.concurrent.ExecutorService)18 Nonnull (javax.annotation.Nonnull)17