Search in sources :

Example 66 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project hbase by apache.

the class TestAsyncTableBatch method testPartialSuccess.

@Test
public void testPartialSuccess() throws IOException, InterruptedException, ExecutionException {
    Admin admin = TEST_UTIL.getAdmin();
    HTableDescriptor htd = admin.getTableDescriptor(TABLE_NAME);
    htd.addCoprocessor(ErrorInjectObserver.class.getName());
    admin.modifyTable(TABLE_NAME, htd);
    AsyncTableBase table = tableGetter.apply(TABLE_NAME);
    table.putAll(Arrays.asList(SPLIT_KEYS).stream().map(k -> new Put(k).addColumn(FAMILY, CQ, k)).collect(Collectors.toList())).get();
    List<CompletableFuture<Result>> futures = table.get(Arrays.asList(SPLIT_KEYS).stream().map(k -> new Get(k)).collect(Collectors.toList()));
    for (int i = 0; i < SPLIT_KEYS.length - 1; i++) {
        assertArrayEquals(SPLIT_KEYS[i], futures.get(i).get().getValue(FAMILY, CQ));
    }
    try {
        futures.get(SPLIT_KEYS.length - 1).get();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(RetriesExhaustedException.class));
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) CompletableFuture(java.util.concurrent.CompletableFuture) ClientTests(org.apache.hadoop.hbase.testclassification.ClientTests) Function(java.util.function.Function) ArrayList(java.util.ArrayList) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) HTableDescriptor(org.apache.hadoop.hbase.HTableDescriptor) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) After(org.junit.After) RegionCoprocessorEnvironment(org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment) Parameterized(org.junit.runners.Parameterized) Cell(org.apache.hadoop.hbase.Cell) Bytes(org.apache.hadoop.hbase.util.Bytes) Before(org.junit.Before) TableName(org.apache.hadoop.hbase.TableName) AfterClass(org.junit.AfterClass) RegionObserver(org.apache.hadoop.hbase.coprocessor.RegionObserver) Parameter(org.junit.runners.Parameterized.Parameter) Assert.assertTrue(org.junit.Assert.assertTrue) LargeTests(org.apache.hadoop.hbase.testclassification.LargeTests) IOException(java.io.IOException) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) Collectors(java.util.stream.Collectors) UncheckedIOException(java.io.UncheckedIOException) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) HBaseTestingUtility(org.apache.hadoop.hbase.HBaseTestingUtility) ForkJoinPool(java.util.concurrent.ForkJoinPool) ObserverContext(org.apache.hadoop.hbase.coprocessor.ObserverContext) Assert.assertEquals(org.junit.Assert.assertEquals) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) HTableDescriptor(org.apache.hadoop.hbase.HTableDescriptor) Test(org.junit.Test)

Example 67 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project hbase by apache.

the class TestAsyncSingleRequestRpcRetryingCaller method testLocateError.

@Test
public void testLocateError() throws IOException, InterruptedException, ExecutionException {
    AtomicBoolean errorTriggered = new AtomicBoolean(false);
    AtomicInteger count = new AtomicInteger(0);
    HRegionLocation loc = CONN.getRegionLocator(TABLE_NAME).getRegionLocation(ROW).get();
    AsyncRegionLocator mockedLocator = new AsyncRegionLocator(CONN, AsyncConnectionImpl.RETRY_TIMER) {

        @Override
        CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row, RegionLocateType locateType, long timeoutNs) {
            if (tableName.equals(TABLE_NAME)) {
                CompletableFuture<HRegionLocation> future = new CompletableFuture<>();
                if (count.getAndIncrement() == 0) {
                    errorTriggered.set(true);
                    future.completeExceptionally(new RuntimeException("Inject error!"));
                } else {
                    future.complete(loc);
                }
                return future;
            } else {
                return super.getRegionLocation(tableName, row, locateType, timeoutNs);
            }
        }

        @Override
        void updateCachedLocation(HRegionLocation loc, Throwable exception) {
        }
    };
    try (AsyncConnectionImpl mockedConn = new AsyncConnectionImpl(CONN.getConfiguration(), CONN.registry, CONN.registry.getClusterId().get(), User.getCurrent()) {

        @Override
        AsyncRegionLocator getLocator() {
            return mockedLocator;
        }
    }) {
        RawAsyncTable table = mockedConn.getRawTableBuilder(TABLE_NAME).setRetryPause(100, TimeUnit.MILLISECONDS).setMaxRetries(5).build();
        table.put(new Put(ROW).addColumn(FAMILY, QUALIFIER, VALUE)).get();
        assertTrue(errorTriggered.get());
        errorTriggered.set(false);
        count.set(0);
        Result result = table.get(new Get(ROW).addColumn(FAMILY, QUALIFIER)).get();
        assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER));
        assertTrue(errorTriggered.get());
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TableName(org.apache.hadoop.hbase.TableName) CompletableFuture(java.util.concurrent.CompletableFuture) HRegionLocation(org.apache.hadoop.hbase.HRegionLocation) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 68 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project neo4j by neo4j.

the class ElectionUtil method waitForLeaderAgreement.

public static MemberId waitForLeaderAgreement(Iterable<RaftMachine> validRafts, long maxTimeMillis) throws InterruptedException, TimeoutException {
    long viewCount = Iterables.count(validRafts);
    Map<MemberId, MemberId> leaderViews = new HashMap<>();
    CompletableFuture<MemberId> futureAgreedLeader = new CompletableFuture<>();
    Collection<Runnable> destructors = new ArrayList<>();
    for (RaftMachine raft : validRafts) {
        destructors.add(leaderViewUpdatingListener(raft, validRafts, leaderViews, viewCount, futureAgreedLeader));
    }
    try {
        try {
            return futureAgreedLeader.get(maxTimeMillis, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    } finally {
        destructors.forEach(Runnable::run);
    }
}
Also used : MemberId(org.neo4j.causalclustering.identity.MemberId) RaftMachine(org.neo4j.causalclustering.core.consensus.RaftMachine) CompletableFuture(java.util.concurrent.CompletableFuture) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException)

Example 69 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project neo4j by neo4j.

the class ReplicatedTokenHolderTest method shouldReplicateTokenRequestForNewToken.

@Test
public void shouldReplicateTokenRequestForNewToken() throws Exception {
    // given
    StorageEngine storageEngine = mockedStorageEngine();
    when(dependencies.resolveDependency(StorageEngine.class)).thenReturn(storageEngine);
    IdGeneratorFactory idGeneratorFactory = mock(IdGeneratorFactory.class);
    IdGenerator idGenerator = mock(IdGenerator.class);
    when(idGenerator.nextId()).thenReturn(1L);
    when(idGeneratorFactory.get(any(IdType.class))).thenReturn(idGenerator);
    TokenRegistry<Token> registry = new TokenRegistry<>("Label");
    int generatedTokenId = 1;
    ReplicatedTokenHolder<Token> tokenHolder = new ReplicatedLabelTokenHolder(registry, (content, trackResult) -> {
        CompletableFuture<Object> completeFuture = new CompletableFuture<>();
        completeFuture.complete(generatedTokenId);
        return completeFuture;
    }, idGeneratorFactory, dependencies);
    // when
    Integer tokenId = tokenHolder.getOrCreateId("name1");
    // then
    assertThat(tokenId, equalTo(generatedTokenId));
}
Also used : IdGeneratorFactory(org.neo4j.kernel.impl.store.id.IdGeneratorFactory) Token(org.neo4j.storageengine.api.Token) IdGenerator(org.neo4j.kernel.impl.store.id.IdGenerator) StorageEngine(org.neo4j.storageengine.api.StorageEngine) IdType(org.neo4j.kernel.impl.store.id.IdType) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Example 70 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project jersey by jersey.

the class InMemoryConnector method apply.

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    CompletableFuture<ClientResponse> future = new CompletableFuture<>();
    try {
        ClientResponse response = apply(request);
        callback.response(response);
        future.complete(response);
    } catch (ProcessingException ex) {
        future.completeExceptionally(ex);
    } catch (Throwable t) {
        callback.failure(t);
        future.completeExceptionally(t);
    }
    return future;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) CompletableFuture(java.util.concurrent.CompletableFuture) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)490 Test (org.junit.Test)152 ArrayList (java.util.ArrayList)88 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)77 List (java.util.List)75 UUID (java.util.UUID)62 Futures (io.pravega.common.concurrent.Futures)60 Map (java.util.Map)59 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)57 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)53 HashMap (java.util.HashMap)52 TimeUnit (java.util.concurrent.TimeUnit)52 Cleanup (lombok.Cleanup)49 Exceptions (io.pravega.common.Exceptions)48 Collectors (java.util.stream.Collectors)48 lombok.val (lombok.val)47 IOException (java.io.IOException)46 Duration (java.time.Duration)46 Slf4j (lombok.extern.slf4j.Slf4j)46 AtomicReference (java.util.concurrent.atomic.AtomicReference)45