Search in sources :

Example 11 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project presto by prestodb.

the class TestThriftIndexPageSource method testGetNextPageTwoConcurrentRequests.

@Test
public void testGetNextPageTwoConcurrentRequests() throws Exception {
    final int splits = 3;
    final int lookupRequestsConcurrency = 2;
    final int rowsPerSplit = 1;
    List<SettableFuture<PrestoThriftPageResult>> futures = IntStream.range(0, splits).mapToObj(i -> SettableFuture.<PrestoThriftPageResult>create()).collect(toImmutableList());
    List<CountDownLatch> signals = IntStream.range(0, splits).mapToObj(i -> new CountDownLatch(1)).collect(toImmutableList());
    TestingThriftService client = new TestingThriftService(rowsPerSplit, false, false) {

        @Override
        public ListenableFuture<PrestoThriftPageResult> getRows(PrestoThriftId splitId, List<String> columns, long maxBytes, PrestoThriftNullableToken nextToken) {
            int key = Ints.fromByteArray(splitId.getId());
            signals.get(key).countDown();
            return futures.get(key);
        }
    };
    ThriftConnectorStats stats = new ThriftConnectorStats();
    long pageSizeReceived = 0;
    ThriftIndexPageSource pageSource = new ThriftIndexPageSource((context, headers) -> client, ImmutableMap.of(), stats, new ThriftIndexHandle(new SchemaTableName("default", "table1"), TupleDomain.all()), ImmutableList.of(column("a", INTEGER)), ImmutableList.of(column("b", INTEGER)), new InMemoryRecordSet(ImmutableList.of(INTEGER), generateKeys(0, splits)), MAX_BYTES_PER_RESPONSE, lookupRequestsConcurrency);
    assertNull(pageSource.getNextPage());
    assertEquals((long) stats.getIndexPageSize().getAllTime().getTotal(), 0);
    signals.get(0).await(1, SECONDS);
    signals.get(1).await(1, SECONDS);
    signals.get(2).await(1, SECONDS);
    assertEquals(signals.get(0).getCount(), 0, "first request wasn't sent");
    assertEquals(signals.get(1).getCount(), 0, "second request wasn't sent");
    assertEquals(signals.get(2).getCount(), 1, "third request shouldn't be sent");
    // at this point first two requests were sent
    assertFalse(pageSource.isFinished());
    assertNull(pageSource.getNextPage());
    assertEquals((long) stats.getIndexPageSize().getAllTime().getTotal(), 0);
    // completing the second request
    futures.get(1).set(pageResult(20, null));
    Page page = pageSource.getNextPage();
    pageSizeReceived += page.getSizeInBytes();
    assertEquals((long) stats.getIndexPageSize().getAllTime().getTotal(), pageSizeReceived);
    assertNotNull(page);
    assertEquals(page.getPositionCount(), 1);
    assertEquals(page.getBlock(0).getInt(0), 20);
    // not complete yet
    assertFalse(pageSource.isFinished());
    // once one of the requests completes the next one should be sent
    signals.get(2).await(1, SECONDS);
    assertEquals(signals.get(2).getCount(), 0, "third request wasn't sent");
    // completing the first request
    futures.get(0).set(pageResult(10, null));
    page = pageSource.getNextPage();
    assertNotNull(page);
    pageSizeReceived += page.getSizeInBytes();
    assertEquals((long) stats.getIndexPageSize().getAllTime().getTotal(), pageSizeReceived);
    assertEquals(page.getPositionCount(), 1);
    assertEquals(page.getBlock(0).getInt(0), 10);
    // still not complete
    assertFalse(pageSource.isFinished());
    // completing the third request
    futures.get(2).set(pageResult(30, null));
    page = pageSource.getNextPage();
    assertNotNull(page);
    pageSizeReceived += page.getSizeInBytes();
    assertEquals((long) stats.getIndexPageSize().getAllTime().getTotal(), pageSizeReceived);
    assertEquals(page.getPositionCount(), 1);
    assertEquals(page.getBlock(0).getInt(0), 30);
    // finished now
    assertTrue(pageSource.isFinished());
    // after completion
    assertNull(pageSource.getNextPage());
    pageSource.close();
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) IntStream(java.util.stream.IntStream) Collections.shuffle(java.util.Collections.shuffle) PrestoThriftNullableSchemaName(com.facebook.presto.thrift.api.connector.PrestoThriftNullableSchemaName) Page(com.facebook.presto.common.Page) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assert.assertNull(org.testng.Assert.assertNull) PrestoThriftNullableTableMetadata(com.facebook.presto.thrift.api.connector.PrestoThriftNullableTableMetadata) PrestoThriftNullableColumnSet(com.facebook.presto.thrift.api.connector.PrestoThriftNullableColumnSet) PrestoThriftBlock.integerData(com.facebook.presto.thrift.api.datatypes.PrestoThriftBlock.integerData) Assert.assertEquals(org.testng.Assert.assertEquals) PrestoThriftSplitBatch(com.facebook.presto.thrift.api.connector.PrestoThriftSplitBatch) Test(org.testng.annotations.Test) CompletableFuture(java.util.concurrent.CompletableFuture) SettableFuture(com.google.common.util.concurrent.SettableFuture) PrestoThriftPageResult(com.facebook.presto.thrift.api.connector.PrestoThriftPageResult) InMemoryRecordSet(com.facebook.presto.spi.InMemoryRecordSet) ArrayList(java.util.ArrayList) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ImmutableList(com.google.common.collect.ImmutableList) PrestoThriftSchemaTableName(com.facebook.presto.thrift.api.connector.PrestoThriftSchemaTableName) PrestoThriftNullableToken(com.facebook.presto.thrift.api.connector.PrestoThriftNullableToken) PrestoThriftTupleDomain(com.facebook.presto.thrift.api.connector.PrestoThriftTupleDomain) Assert.assertFalse(org.testng.Assert.assertFalse) Type(com.facebook.presto.common.type.Type) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) PrestoThriftService(com.facebook.presto.thrift.api.connector.PrestoThriftService) PrestoThriftServiceException(com.facebook.presto.thrift.api.connector.PrestoThriftServiceException) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Assert.assertNotNull(org.testng.Assert.assertNotNull) PrestoThriftId(com.facebook.presto.thrift.api.connector.PrestoThriftId) PrestoThriftSplit(com.facebook.presto.thrift.api.connector.PrestoThriftSplit) Ints(com.google.common.primitives.Ints) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) PrestoThriftInteger(com.facebook.presto.thrift.api.datatypes.PrestoThriftInteger) Assert.assertTrue(org.testng.Assert.assertTrue) Block(com.facebook.presto.common.block.Block) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) PrestoThriftId(com.facebook.presto.thrift.api.connector.PrestoThriftId) PrestoThriftNullableToken(com.facebook.presto.thrift.api.connector.PrestoThriftNullableToken) PrestoThriftPageResult(com.facebook.presto.thrift.api.connector.PrestoThriftPageResult) Page(com.facebook.presto.common.Page) CountDownLatch(java.util.concurrent.CountDownLatch) SchemaTableName(com.facebook.presto.spi.SchemaTableName) PrestoThriftSchemaTableName(com.facebook.presto.thrift.api.connector.PrestoThriftSchemaTableName) InMemoryRecordSet(com.facebook.presto.spi.InMemoryRecordSet) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) Test(org.testng.annotations.Test)

Example 12 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project presto by prestodb.

the class ExchangeClient method addPages.

private boolean addPages(List<SerializedPage> pages) {
    // Compute stats before acquiring the lock
    long pagesRetainedSizeInBytes = 0;
    long responseSize = 0;
    for (SerializedPage page : pages) {
        pagesRetainedSizeInBytes += page.getRetainedSizeInBytes();
        responseSize += page.getSizeInBytes();
    }
    List<SettableFuture<?>> notify = ImmutableList.of();
    synchronized (this) {
        if (isClosed() || isFailed()) {
            return false;
        }
        if (!pages.isEmpty()) {
            pageBuffer.addAll(pages);
            bufferRetainedSizeInBytes += pagesRetainedSizeInBytes;
            maxBufferRetainedSizeInBytes = max(maxBufferRetainedSizeInBytes, bufferRetainedSizeInBytes);
            systemMemoryContext.setBytes(bufferRetainedSizeInBytes);
            // Notify pending listeners that a page has been added
            notify = ImmutableList.copyOf(blockedCallers);
            blockedCallers.clear();
        }
        successfulRequests++;
        responseSizeExponentialMovingAverage.update(responseSize);
    }
    // Trigger notifications after releasing the lock
    notifyListeners(notify);
    return true;
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) SerializedPage(com.facebook.presto.spi.page.SerializedPage)

Example 13 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project presto by prestodb.

the class HivePageSink method doFinish.

private ListenableFuture<Collection<Slice>> doFinish() {
    ImmutableList.Builder<PartitionUpdate> partitionUpdatesBuilder = ImmutableList.builder();
    List<Callable<Object>> verificationTasks = new ArrayList<>();
    for (HiveWriter writer : writers) {
        writer.commit();
        partitionUpdatesBuilder.add(writer.getPartitionUpdate());
        writer.getVerificationTask().map(Executors::callable).ifPresent(verificationTasks::add);
    }
    List<PartitionUpdate> partitionUpdates = partitionUpdatesBuilder.build();
    boolean optimizedPartitionUpdateSerializationEnabled = isOptimizedPartitionUpdateSerializationEnabled(session);
    if (optimizedPartitionUpdateSerializationEnabled) {
        // Merge multiple partition updates for a single partition into one.
        // Multiple partition updates for a single partition are produced when writing into a bucketed table.
        // Merged partition updates will contain multiple items in the fileWriteInfos list (one per bucket).
        // This optimization should be enabled only together with the optimized serialization (compression + binary encoding).
        // Since serialized fragments will be transmitted as Presto pages serializing a merged partition update to JSON without
        // compression is unsafe, as it may cross the maximum page size limit.
        partitionUpdates = mergePartitionUpdates(partitionUpdates);
    }
    ImmutableList.Builder<Slice> serializedPartitionUpdatesBuilder = ImmutableList.builder();
    for (PartitionUpdate partitionUpdate : partitionUpdates) {
        byte[] serializedBytes;
        if (optimizedPartitionUpdateSerializationEnabled) {
            serializedBytes = serializeZstdCompressed(partitionUpdateSmileCodec, partitionUpdate);
        } else {
            serializedBytes = partitionUpdateCodec.toBytes(partitionUpdate);
        }
        serializedPartitionUpdatesBuilder.add(wrappedBuffer(serializedBytes));
    }
    List<Slice> serializedPartitionUpdates = serializedPartitionUpdatesBuilder.build();
    writtenBytes = writers.stream().mapToLong(HiveWriter::getWrittenBytes).sum();
    validationCpuNanos = writers.stream().mapToLong(HiveWriter::getValidationCpuNanos).sum();
    if (waitForFileRenaming && verificationTasks.isEmpty()) {
        // Use CopyOnWriteArrayList to prevent race condition when callbacks try to add partitionUpdates to this list
        List<Slice> partitionUpdatesWithRenamedFileNames = new CopyOnWriteArrayList<>();
        List<ListenableFuture<?>> futures = new ArrayList<>();
        for (int i = 0; i < writers.size(); i++) {
            int writerIndex = i;
            ListenableFuture<?> fileNameFuture = toListenableFuture(hiveMetadataUpdater.getMetadataResult(writerIndex));
            SettableFuture renamingFuture = SettableFuture.create();
            futures.add(renamingFuture);
            addSuccessCallback(fileNameFuture, obj -> renameFiles((String) obj, writerIndex, renamingFuture, partitionUpdatesWithRenamedFileNames));
        }
        return Futures.transform(Futures.allAsList(futures), input -> partitionUpdatesWithRenamedFileNames, directExecutor());
    }
    if (verificationTasks.isEmpty()) {
        return Futures.immediateFuture(serializedPartitionUpdates);
    }
    try {
        List<ListenableFuture<?>> futures = writeVerificationExecutor.invokeAll(verificationTasks).stream().map(future -> (ListenableFuture<?>) future).collect(toList());
        return Futures.transform(Futures.allAsList(futures), input -> serializedPartitionUpdates, directExecutor());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) MoreFutures(com.facebook.airlift.concurrent.MoreFutures) JsonCodec(com.facebook.airlift.json.JsonCodec) Page(com.facebook.presto.common.Page) HiveBucketFunction.createPrestoNativeBucketFunction(com.facebook.presto.hive.HiveBucketFunction.createPrestoNativeBucketFunction) SettableFuture(com.google.common.util.concurrent.SettableFuture) Slices.wrappedBuffer(io.airlift.slice.Slices.wrappedBuffer) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) HiveSessionProperties.isOptimizedPartitionUpdateSerializationEnabled(com.facebook.presto.hive.HiveSessionProperties.isOptimizedPartitionUpdateSerializationEnabled) Map(java.util.Map) ConnectorPageSink(com.facebook.presto.spi.ConnectorPageSink) PageIndexerFactory(com.facebook.presto.spi.PageIndexerFactory) Path(org.apache.hadoop.fs.Path) FileWriteInfo(com.facebook.presto.hive.PartitionUpdate.FileWriteInfo) Object2IntOpenHashMap(it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap) PartitionUpdate.mergePartitionUpdates(com.facebook.presto.hive.PartitionUpdate.mergePartitionUpdates) ExtendedFileSystem(com.facebook.presto.hive.filesystem.ExtendedFileSystem) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) HIVE_TOO_MANY_OPEN_PARTITIONS(com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) ConnectorSession(com.facebook.presto.spi.ConnectorSession) List(java.util.List) MoreFutures.addSuccessCallback(com.facebook.airlift.concurrent.MoreFutures.addSuccessCallback) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) IntArrayBlockBuilder(com.facebook.presto.common.block.IntArrayBlockBuilder) Optional(java.util.Optional) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Logger(com.facebook.airlift.log.Logger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Slice(io.airlift.slice.Slice) HIVE_WRITER_CLOSE_ERROR(com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) HiveBucketFunction.createHiveCompatibleBucketFunction(com.facebook.presto.hive.HiveBucketFunction.createHiveCompatibleBucketFunction) PrestoException(com.facebook.presto.spi.PrestoException) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) SmileCodec(com.facebook.airlift.json.smile.SmileCodec) TypeManager(com.facebook.presto.common.type.TypeManager) Objects.requireNonNull(java.util.Objects.requireNonNull) HiveSessionProperties.isFileRenamingEnabled(com.facebook.presto.hive.HiveSessionProperties.isFileRenamingEnabled) Type(com.facebook.presto.common.type.Type) PageIndexer(com.facebook.presto.spi.PageIndexer) IOException(java.io.IOException) Ints(com.google.common.primitives.Ints) MoreFutures.toListenableFuture(com.facebook.airlift.concurrent.MoreFutures.toListenableFuture) Futures(com.google.common.util.concurrent.Futures) HIVE_FILESYSTEM_ERROR(com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR) Collectors.toList(java.util.stream.Collectors.toList) Object2IntMap(it.unimi.dsi.fastutil.objects.Object2IntMap) Block(com.facebook.presto.common.block.Block) HiveUtil.serializeZstdCompressed(com.facebook.presto.hive.HiveUtil.serializeZstdCompressed) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Callable(java.util.concurrent.Callable) Slice(io.airlift.slice.Slice) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) MoreFutures.toListenableFuture(com.facebook.airlift.concurrent.MoreFutures.toListenableFuture) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 14 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project azure-tools-for-java by Microsoft.

the class AddDependencyAction method onActionPerformed.

@Override
public boolean onActionPerformed(@NotNull AnActionEvent event, @Nullable Operation operation) {
    final Module module = event.getData(LangDataKeys.MODULE);
    final Project project = module.getProject();
    final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
    final MavenProject mavenProject = projectsManager.findProject(module);
    if (mavenProject == null) {
        PluginUtil.showErrorNotificationProject(project, "Error", String.format("Project '%s' is not a maven project.", project.getName()));
        return true;
    }
    final AzureString title = AzureOperationBundle.title("springcloud.update_dependency", project.getName());
    AzureTaskManager.getInstance().runInBackground(new AzureTask(project, title, true, () -> {
        ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
        progressIndicator.setText("Syncing maven project " + project.getName());
        final SettableFuture<Boolean> isDirty = SettableFuture.create();
        AzureTaskManager.getInstance().runAndWait(() -> {
            ProjectNotificationAware notificationAware = ProjectNotificationAware.getInstance(project);
            isDirty.set(notificationAware.isNotificationVisible());
            if (notificationAware.isNotificationVisible()) {
                ExternalSystemProjectTracker projectTracker = ExternalSystemProjectTracker.getInstance(project);
                projectTracker.scheduleProjectRefresh();
            }
        });
        try {
            if (isDirty.get().booleanValue()) {
                projectsManager.forceUpdateProjects(Collections.singletonList(mavenProject)).get();
            }
        } catch (InterruptedException | ExecutionException e) {
            PluginUtil.showErrorNotification("Error", "Failed to update project due to error: " + e.getMessage());
            return;
        }
        try {
            progressIndicator.setText("Check existing dependencies");
            final String evaluateEffectivePom = MavenUtils.evaluateEffectivePom(project, mavenProject);
            ProgressManager.checkCanceled();
            if (StringUtils.isEmpty(evaluateEffectivePom)) {
                PluginUtil.showErrorNotificationProject(project, "Error", "Failed to evaluate effective pom.");
                return;
            }
            final String springBootVer = getMavenLibraryVersion(mavenProject, SPRING_BOOT_GROUP_ID, "spring-boot-autoconfigure");
            if (StringUtils.isEmpty(springBootVer)) {
                throw new AzureExecutionException(String.format("Module %s is not a spring-boot application.", module.getName()));
            }
            progressIndicator.setText("Get latest versions ...");
            SpringCloudDependencyManager dependencyManager = new SpringCloudDependencyManager(evaluateEffectivePom);
            Map<String, DependencyArtifact> versionMaps = dependencyManager.getDependencyVersions();
            Map<String, DependencyArtifact> managerDependencyVersionsMaps = dependencyManager.getDependencyManagementVersions();
            // given the spring-cloud-commons is greater or equal to 2.2.5.RELEASE, we should not add spring-cloud-starter-azure-spring-cloud-client
            // because the code is already merged into spring repo: https://github.com/spring-cloud/spring-cloud-commons/pull/803
            boolean noAzureSpringCloudClientDependency = shouldNotAddAzureSpringCloudClientDependency(versionMaps) || shouldNotAddAzureSpringCloudClientDependency(managerDependencyVersionsMaps);
            ProgressManager.checkCanceled();
            final List<DependencyArtifact> versionChanges = calculateVersionChanges(springBootVer, noAzureSpringCloudClientDependency, versionMaps);
            if (versionChanges.isEmpty()) {
                PluginUtil.showInfoNotificationProject(project, "Your project is update-to-date.", "No updates are needed.");
                return;
            }
            progressIndicator.setText("Applying versions ...");
            final File pomFile = new File(mavenProject.getFile().getCanonicalPath());
            ProgressManager.checkCanceled();
            if (applyVersionChanges(dependencyManager, pomFile, springBootVer, managerDependencyVersionsMaps, versionChanges)) {
                noticeUserVersionChanges(project, pomFile, versionChanges);
            } else {
                PluginUtil.showInfoNotificationProject(project, "Your project is update-to-date.", "No updates are needed.");
            }
        } catch (DocumentException | IOException | AzureExecutionException | MavenProcessCanceledException e) {
            PluginUtil.showErrorNotification("Error", "Failed to update Azure Spring Cloud dependencies due to error: " + e.getMessage());
        }
    }));
    return false;
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) MavenProjectsManager(org.jetbrains.idea.maven.project.MavenProjectsManager) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) Project(com.intellij.openapi.project.Project) MavenProject(org.jetbrains.idea.maven.project.MavenProject) ProjectNotificationAware(com.intellij.openapi.externalSystem.autoimport.ProjectNotificationAware) MavenProject(org.jetbrains.idea.maven.project.MavenProject) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) ExternalSystemProjectTracker(com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker) ArrayList(java.util.ArrayList) List(java.util.List) Module(com.intellij.openapi.module.Module) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) Map(java.util.Map) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File)

Example 15 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project storm by apache.

the class AsyncExecutor method execAsync.

/**
 * Asynchronously executes all statements associated to the specified input.
 * The input will be passed to handler#onSuccess once all queries succeed or to handler#onFailure if any one of them fails.
 */
public List<SettableFuture<T>> execAsync(List<Statement> statements, final T input) {
    List<SettableFuture<T>> settableFutures = new ArrayList<>(statements.size());
    for (Statement s : statements) {
        settableFutures.add(execAsync(s, input, AsyncResultHandler.NO_OP_HANDLER));
    }
    ListenableFuture<List<T>> allAsList = Futures.allAsList(settableFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<T>>() {

        @Override
        public void onSuccess(List<T> inputs) {
            handler.success(input);
        }

        @Override
        public void onFailure(Throwable t) {
            handler.failure(t, input);
        }
    }, executorService);
    return settableFutures;
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) Statement(com.datastax.driver.core.Statement) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

SettableFuture (com.google.common.util.concurrent.SettableFuture)46 Test (org.junit.Test)25 ArrayList (java.util.ArrayList)15 List (java.util.List)15 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)14 File (java.io.File)12 IOException (java.io.IOException)10 TimeUnit (java.util.concurrent.TimeUnit)10 Futures (com.google.common.util.concurrent.Futures)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 ExecutionException (java.util.concurrent.ExecutionException)8 FutureCallback (com.google.common.util.concurrent.FutureCallback)7 Before (org.junit.Before)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 Throwables (com.google.common.base.Throwables)5 ImmutableList (com.google.common.collect.ImmutableList)5 Assert.assertSame (org.junit.Assert.assertSame)5 Mock (org.mockito.Mock)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5