use of java.util.function.BiConsumer in project redisson by redisson.
the class CommandAsyncService method allAsync.
private <T, R> RFuture<R> allAsync(boolean readOnlyMode, Codec codec, RedisCommand<T> command, SlotCallback<T, R> callback, Object... params) {
RPromise<R> mainPromise = new RedissonPromise<R>();
Collection<MasterSlaveEntry> nodes = connectionManager.getEntrySet();
AtomicInteger counter = new AtomicInteger(nodes.size());
BiConsumer<T, Throwable> listener = new BiConsumer<T, Throwable>() {
@Override
public void accept(T result, Throwable u) {
if (u != null && !(u instanceof RedisRedirectException)) {
mainPromise.tryFailure(u);
return;
}
if (u instanceof RedisRedirectException) {
result = command.getConvertor().convert(result);
}
if (callback != null) {
callback.onSlotResult(result);
}
if (counter.decrementAndGet() == 0) {
if (callback != null) {
mainPromise.trySuccess(callback.onFinish());
} else {
mainPromise.trySuccess(null);
}
}
}
};
for (MasterSlaveEntry entry : nodes) {
RFuture<T> promise = async(readOnlyMode, new NodeSource(entry), codec, command, params, true, false);
promise.whenComplete(listener);
}
return mainPromise;
}
use of java.util.function.BiConsumer in project cassandra by apache.
the class CASTest method consistencyAfterWriteTimeoutTest.
/**
* Base test to ensure that if a write times out but with a proposal accepted by some nodes (less then quorum), and
* a following SERIAL operation does not observe that write (the node having accepted it do not participate in that
* following operation), then that write is never applied, even when the nodes having accepted the original proposal
* participate.
*
* <p>In other words, if an operation timeout, it may or may not be applied, but that "fate" is persistently decided
* by the very SERIAL operation that "succeed" (in the sense of 'not timing out or throwing some other exception').
*
* @param postTimeoutOperation1 a SERIAL operation executed after an initial write that inserts the row [0, 0] times
* out. It is executed with a QUORUM of nodes that have _not_ see the timed out
* proposal, and so that operation should expect that the [0, 0] write has not taken
* place.
* @param postTimeoutOperation2 a 2nd SERIAL operation executed _after_ {@code postTimeoutOperation1}, with no
* write executed between the 2 operation. Contrarily to the 1st operation, the QORUM
* for this operation _will_ include the node that got the proposal for the [0, 0]
* insert but didn't participated to {@code postTimeoutOperation1}}. That operation
* should also no witness that [0, 0] write (since {@code postTimeoutOperation1}
* didn't).
* @param loseCommitOfOperation1 if {@code true}, the test will also drop the "commits" messages for
* {@code postTimeoutOperation1}. In general, the test should behave the same with or
* without that flag since a value is decided as soon as it has been "accepted by
* quorum" and the commits should always be properly replayed.
*/
private void consistencyAfterWriteTimeoutTest(BiConsumer<String, ICoordinator> postTimeoutOperation1, BiConsumer<String, ICoordinator> postTimeoutOperation2, boolean loseCommitOfOperation1) throws IOException {
// not about performance, this is probably ok, even if we ideally should dug into the underlying reason.
try (Cluster cluster = init(Cluster.create(3, config -> config.set("write_request_timeout", "4000ms").set("cas_contention_timeout", CONTENTION_TIMEOUT)))) {
String table = KEYSPACE + ".t";
cluster.schemaChange("CREATE TABLE " + table + " (k int PRIMARY KEY, v int)");
// We do a CAS insertion, but have with the PROPOSE message dropped on node 1 and 2. The CAS will not get
// through and should timeout. Importantly, node 3 does receive and answer the PROPOSE.
IMessageFilters.Filter dropProposeFilter = cluster.filters().inbound().verbs(PAXOS_PROPOSE_REQ.id).from(3).to(1, 2).drop();
try {
// NOTE: the consistency below is the "commit" one, so it doesn't matter at all here.
// NOTE 2: we use node 3 as coordinator because message filters don't currently work for locally
// delivered messages and as we want to drop messages to 1 and 2, we can't use them.
cluster.coordinator(3).execute("INSERT INTO " + table + "(k, v) VALUES (0, 0) IF NOT EXISTS", ConsistencyLevel.ONE);
fail("The insertion should have timed-out");
} catch (Exception e) {
// be improved at the dtest API level.
if (!e.getClass().getSimpleName().equals("CasWriteTimeoutException"))
throw e;
} finally {
dropProposeFilter.off();
}
// Isolates node 3 and executes the SERIAL operation. As neither node 1 or 2 got the initial insert proposal,
// there is nothing to "replay" and the operation should assert the table is still empty.
IMessageFilters.Filter ignoreNode3Filter = cluster.filters().verbs(paxosAndReadVerbs()).to(3).drop();
IMessageFilters.Filter dropCommitFilter = null;
if (loseCommitOfOperation1) {
dropCommitFilter = cluster.filters().verbs(PAXOS_COMMIT_REQ.id).to(1, 2).drop();
}
try {
postTimeoutOperation1.accept(table, cluster.coordinator(1));
} finally {
ignoreNode3Filter.off();
if (dropCommitFilter != null)
dropCommitFilter.off();
}
// Node 3 is now back and we isolate node 2 to ensure the next read hits node 1 and 3.
// What we want to ensure is that despite node 3 having the initial insert in its paxos state in a position of
// being replayed, that insert is _not_ replayed (it would contradict serializability since the previous
// operation asserted nothing was inserted). It is this execution that failed before CASSANDRA-12126.
IMessageFilters.Filter ignoreNode2Filter = cluster.filters().verbs(paxosAndReadVerbs()).to(2).drop();
try {
postTimeoutOperation2.accept(table, cluster.coordinator(1));
} finally {
ignoreNode2Filter.off();
}
}
}
use of java.util.function.BiConsumer in project cassandra by apache.
the class CellSpecTest method data.
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
TableMetadata table = TableMetadata.builder("testing", "testing").addPartitionKeyColumn("pk", BytesType.instance).build();
byte[] rawBytes = { 0, 1, 2, 3, 4, 5, 6 };
ByteBuffer bbBytes = ByteBuffer.wrap(rawBytes);
NativePool pool = new NativePool(1024, 1024, 1, () -> ImmediateFuture.success(true));
NativeAllocator allocator = pool.newAllocator(null);
OpOrder order = new OpOrder();
List<Cell<?>> tests = new ArrayList<>();
BiConsumer<ColumnMetadata, CellPath> fn = (column, path) -> {
tests.add(new ArrayCell(column, 1234, 1, 1, rawBytes, path));
tests.add(new BufferCell(column, 1234, 1, 1, bbBytes, path));
tests.add(new NativeCell(allocator, order.getCurrent(), column, 1234, 1, 1, bbBytes, path));
};
// simple
fn.accept(ColumnMetadata.regularColumn(table, bytes("simple"), BytesType.instance), null);
// complex
// seems NativeCell does not allow CellPath.TOP, or CellPath.BOTTOM
fn.accept(ColumnMetadata.regularColumn(table, bytes("complex"), ListType.getInstance(BytesType.instance, true)), CellPath.create(bytes(UUIDGen.getTimeUUID())));
return tests.stream().map(a -> new Object[] { a.getClass().getSimpleName() + ":" + (a.path() == null ? "simple" : "complex"), a }).collect(Collectors.toList());
}
use of java.util.function.BiConsumer in project neo4j by neo4j.
the class RecordLoadingTest method shouldReturnsFalseOnMissingToken.
@Test
void shouldReturnsFalseOnMissingToken() {
// given
NodeRecord entity = new NodeRecord(0);
TokenHolder tokenHolder = new DelegatingTokenHolder(new ReadOnlyTokenCreator(), "Test");
TokenStore<PropertyKeyTokenRecord> store = mock(TokenStore.class);
BiConsumer noopReporter = mock(BiConsumer.class);
// when
boolean valid = RecordLoading.checkValidToken(entity, 0, tokenHolder, store, noopReporter, noopReporter, CursorContext.NULL);
// then
assertFalse(valid);
}
use of java.util.function.BiConsumer in project flink by apache.
the class ApplicationDispatcherBootstrapTest method testSubmitFailedJobOnApplicationError.
private void testSubmitFailedJobOnApplicationError(Configuration configuration, BiConsumer<JobID, Throwable> failedJobAssertion) throws Exception {
final CompletableFuture<Void> submitted = new CompletableFuture<>();
final TestingDispatcherGateway dispatcherGateway = TestingDispatcherGateway.newBuilder().setSubmitFailedFunction((jobId, jobName, t) -> {
try {
failedJobAssertion.accept(jobId, t);
submitted.complete(null);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Throwable assertion) {
submitted.completeExceptionally(assertion);
return FutureUtils.completedExceptionally(assertion);
}
}).setRequestJobStatusFunction(jobId -> submitted.thenApply(ignored -> JobStatus.FAILED)).setRequestJobResultFunction(jobId -> submitted.thenApply(ignored -> createJobResult(jobId, ApplicationStatus.FAILED))).build();
final ApplicationDispatcherBootstrap bootstrap = new ApplicationDispatcherBootstrap(FailingJob.getProgram(), Collections.emptyList(), configuration, dispatcherGateway, scheduledExecutor, exception -> {
});
bootstrap.getBootstrapCompletionFuture().get();
}
Aggregations