Search in sources :

Example 36 with ListeningExecutorService

use of com.google.common.util.concurrent.ListeningExecutorService in project bazel by bazelbuild.

the class AndroidResourceMerger method mergeData.

/** Merges all secondary resources with the primary resources. */
static MergedAndroidData mergeData(final ParsedAndroidData primary, final Path primaryManifest, final List<? extends SerializedAndroidData> direct, final List<? extends SerializedAndroidData> transitive, final Path resourcesOut, final Path assetsOut, @Nullable final PngCruncher cruncher, final VariantType type, @Nullable final Path symbolsOut, @Nullable AndroidResourceClassWriter rclassWriter) throws MergingException {
    Stopwatch timer = Stopwatch.createStarted();
    final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(15));
    try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {
        AndroidDataMerger merger = AndroidDataMerger.createWithPathDeduplictor(executorService);
        UnwrittenMergedAndroidData merged = merger.loadAndMerge(transitive, direct, primary, primaryManifest, type != VariantType.LIBRARY);
        logger.fine(String.format("merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
        timer.reset().start();
        if (symbolsOut != null) {
            AndroidDataSerializer serializer = AndroidDataSerializer.create();
            merged.serializeTo(serializer);
            serializer.flushTo(symbolsOut);
            logger.fine(String.format("serialize merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        if (rclassWriter != null) {
            merged.writeResourceClass(rclassWriter);
            logger.fine(String.format("write classes finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        AndroidDataWriter writer = AndroidDataWriter.createWith(resourcesOut.getParent(), resourcesOut, assetsOut, cruncher, executorService);
        return merged.write(writer);
    } catch (IOException e) {
        throw MergingException.wrapException(e).build();
    } finally {
        logger.fine(String.format("write merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    }
}
Also used : Closeable(java.io.Closeable) Stopwatch(com.google.common.base.Stopwatch) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) IOException(java.io.IOException)

Example 37 with ListeningExecutorService

use of com.google.common.util.concurrent.ListeningExecutorService in project buck by facebook.

the class MoreSuppliersTest method weakMemoizeShouldRunDelegateOnlyOnceOnConcurrentAccess.

@Test
public void weakMemoizeShouldRunDelegateOnlyOnceOnConcurrentAccess() throws Exception {
    final int numFetchers = 10;
    final Semaphore semaphore = new Semaphore(0);
    class TestDelegate implements Supplier<Object> {

        private int timesCalled = 0;

        public int getTimesCalled() {
            return timesCalled;
        }

        @Override
        public Object get() {
            try {
                // Wait for all the fetch threads to be ready.
                semaphore.acquire(numFetchers);
                // Give other threads a chance to catch up.
                Thread.sleep(50);
                timesCalled++;
                return new Object();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                semaphore.release(numFetchers);
            }
        }
    }
    TestDelegate delegate = new TestDelegate();
    final Supplier<Object> supplier = MoreSuppliers.weakMemoize(delegate);
    ExecutorService threadPool = Executors.newFixedThreadPool(numFetchers);
    try {
        ListeningExecutorService executor = MoreExecutors.listeningDecorator(threadPool);
        class Fetcher implements Callable<Object> {

            @Override
            public Object call() {
                // Signal that this particular fetcher is ready.
                semaphore.release();
                return supplier.get();
            }
        }
        ImmutableList.Builder<Callable<Object>> fetcherBuilder = ImmutableList.builder();
        for (int i = 0; i < numFetchers; i++) {
            fetcherBuilder.add(new Fetcher());
        }
        @SuppressWarnings("unchecked") List<ListenableFuture<Object>> futures = (List<ListenableFuture<Object>>) (List<?>) executor.invokeAll(fetcherBuilder.build());
        // Wait for all fetchers to finish.
        List<Object> results = Futures.allAsList(futures).get();
        Assert.assertEquals("should only have been called once", 1, delegate.getTimesCalled());
        Assert.assertThat("all result items are the same", ImmutableSet.copyOf(results), Matchers.hasSize(1));
        Preconditions.checkState(threadPool.shutdownNow().isEmpty(), "All jobs should have completed");
        Preconditions.checkState(threadPool.awaitTermination(10, TimeUnit.SECONDS), "Thread pool should terminate in a reasonable amount of time");
    } finally {
        // In case exceptions were thrown, attempt to shut down the thread pool.
        threadPool.shutdownNow();
        threadPool.awaitTermination(10, TimeUnit.SECONDS);
    }
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) Semaphore(java.util.concurrent.Semaphore) Callable(java.util.concurrent.Callable) ExecutorService(java.util.concurrent.ExecutorService) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Supplier(com.google.common.base.Supplier) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Test(org.junit.Test)

Example 38 with ListeningExecutorService

use of com.google.common.util.concurrent.ListeningExecutorService in project buck by facebook.

the class AsyncCloseableTest method testCloseAsync.

@Test
public void testCloseAsync() throws Exception {
    ListeningExecutorService directExecutor = MoreExecutors.newDirectExecutorService();
    final AtomicBoolean didClose = new AtomicBoolean(false);
    try (AsyncCloseable asyncCloseable = new AsyncCloseable(directExecutor)) {
        asyncCloseable.closeAsync(() -> didClose.set(true));
    }
    assertThat(didClose.get(), Matchers.is(true));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Test(org.junit.Test)

Example 39 with ListeningExecutorService

use of com.google.common.util.concurrent.ListeningExecutorService in project buck by facebook.

the class ResourcePoolTest method exceptionOnResourceUsageWithRetireHandling.

@Test
public void exceptionOnResourceUsageWithRetireHandling() throws Exception {
    try (Fixture f = new Fixture(/* maxResources */
    1, ResourcePool.ResourceUsageErrorPolicy.RETIRE)) {
        ListeningExecutorService executorService = MoreExecutors.newDirectExecutorService();
        List<ListenableFuture<TestResource>> results = Stream.of(0, 1, 2).map(i -> f.getPool().scheduleOperationWithResource(r -> {
            if (i == 1) {
                throw new TestException();
            }
            return r;
        }, executorService)).collect(Collectors.toList());
        Futures.successfulAsList(results).get();
        assertThat(f.getCreatedResources().get(), equalTo(f.getMaxResources() + 1));
        // First request gets the first resource (id == 0), second request errors out causing the
        // resource to be retired and the third request gets a new resource (id == 1).
        assertThat(results.get(0).get().getTestResourceId(), equalTo(0));
        assertThat(results.get(2).get().getTestResourceId(), equalTo(1));
        expectedException.expectCause(Matchers.instanceOf(TestException.class));
        results.get(1).get();
    }
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Matchers(org.hamcrest.Matchers) Set(java.util.Set) Test(org.junit.Test) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Rule(org.junit.Rule) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Matchers.equalTo(org.hamcrest.Matchers.equalTo) ExpectedException(org.junit.rules.ExpectedException) Assert.assertEquals(org.junit.Assert.assertEquals) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Test(org.junit.Test)

Example 40 with ListeningExecutorService

use of com.google.common.util.concurrent.ListeningExecutorService in project ddf by codice.

the class MetadataConfigurationParser method buildEntityDescriptor.

private void buildEntityDescriptor(String entityDescription) throws IOException {
    EntityDescriptor entityDescriptor = null;
    entityDescription = entityDescription.trim();
    if (entityDescription.startsWith(HTTPS) || entityDescription.startsWith(HTTP)) {
        if (entityDescription.startsWith(HTTP)) {
            LOGGER.warn("Retrieving metadata via HTTP instead of HTTPS. The metadata configuration is unsafe!!!");
        }
        PropertyResolver propertyResolver = new PropertyResolver(entityDescription);
        HttpTransport httpTransport = new NetHttpTransport();
        HttpRequest httpRequest = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(propertyResolver.getResolvedString()));
        httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setBackOffRequired(HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ALWAYS));
        httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
        ListenableFuture<HttpResponse> httpResponseFuture = service.submit(httpRequest::execute);
        Futures.addCallback(httpResponseFuture, new FutureCallback<HttpResponse>() {

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse != null) {
                    try {
                        String parsedResponse = httpResponse.parseAsString();
                        buildEntityDescriptor(parsedResponse);
                    } catch (IOException e) {
                        LOGGER.info("Unable to parse metadata from: {}", httpResponse.getRequest().getUrl().toString(), e);
                    }
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOGGER.info("Unable to retrieve metadata.", throwable);
            }
        });
        service.shutdown();
    } else if (entityDescription.startsWith(FILE + System.getProperty("ddf.home"))) {
        String pathStr = StringUtils.substringAfter(entityDescription, FILE);
        Path path = Paths.get(pathStr);
        if (Files.isReadable(path)) {
            try (InputStream fileInputStream = Files.newInputStream(path)) {
                entityDescriptor = readEntityDescriptor(new InputStreamReader(fileInputStream, "UTF-8"));
            }
        }
    } else if (entityDescription.startsWith("<") && entityDescription.endsWith(">")) {
        entityDescriptor = readEntityDescriptor(new StringReader(entityDescription));
    } else {
        LOGGER.info("Skipping unknown metadata configuration value: {}", entityDescription);
    }
    if (entityDescriptor != null) {
        entityDescriptorMap.put(entityDescriptor.getEntityID(), entityDescriptor);
        if (updateCallback != null) {
            updateCallback.accept(entityDescriptor);
        }
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Path(java.nio.file.Path) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) PropertyResolver(org.codice.ddf.configuration.PropertyResolver) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) StringReader(java.io.StringReader) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService)

Aggregations

ListeningExecutorService (com.google.common.util.concurrent.ListeningExecutorService)201 Test (org.junit.Test)115 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)75 ArrayList (java.util.ArrayList)43 CountDownLatch (java.util.concurrent.CountDownLatch)29 ExecutorService (java.util.concurrent.ExecutorService)28 IOException (java.io.IOException)25 ExecutionException (java.util.concurrent.ExecutionException)25 Interval (org.joda.time.Interval)25 DateTime (org.joda.time.DateTime)23 List (java.util.List)21 Callable (java.util.concurrent.Callable)20 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)20 DruidServer (io.druid.client.DruidServer)18 DataSegment (io.druid.timeline.DataSegment)18 DruidServer (org.apache.druid.client.DruidServer)17 ImmutableMap (com.google.common.collect.ImmutableMap)16 File (java.io.File)16 Map (java.util.Map)16 ApplicationId (org.apache.hadoop.yarn.api.records.ApplicationId)15