Search in sources :

Example 76 with BiConsumer

use of java.util.function.BiConsumer in project beam by apache.

the class ExecutableStageDoFnOperatorTest method testWatermarkHandling.

@Test
public void testWatermarkHandling() throws Exception {
    TupleTag<Integer> mainOutput = new TupleTag<>("main-output");
    DoFnOperator.MultiOutputOutputManagerFactory<Integer> outputManagerFactory = new DoFnOperator.MultiOutputOutputManagerFactory(mainOutput, VoidCoder.of(), new SerializablePipelineOptions(FlinkPipelineOptions.defaults()));
    ExecutableStageDoFnOperator<KV<String, Integer>, Integer> operator = getOperator(mainOutput, Collections.emptyList(), outputManagerFactory, WindowingStrategy.of(FixedWindows.of(Duration.millis(10))), StringUtf8Coder.of(), WindowedValue.getFullCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()), IntervalWindow.getCoder()));
    KeyedOneInputStreamOperatorTestHarness<String, WindowedValue<KV<String, Integer>>, WindowedValue<Integer>> testHarness = new KeyedOneInputStreamOperatorTestHarness<>(operator, val -> val.getValue().getKey(), new CoderTypeInformation<>(StringUtf8Coder.of(), FlinkPipelineOptions.defaults()));
    RemoteBundle bundle = Mockito.mock(RemoteBundle.class);
    when(bundle.getInputReceivers()).thenReturn(ImmutableMap.<String, FnDataReceiver<WindowedValue>>builder().put("input", Mockito.mock(FnDataReceiver.class)).build());
    when(bundle.getTimerReceivers()).thenReturn(ImmutableMap.<KV<String, String>, FnDataReceiver<WindowedValue>>builder().put(KV.of("transform", "timer"), Mockito.mock(FnDataReceiver.class)).put(KV.of("transform", "timer2"), Mockito.mock(FnDataReceiver.class)).put(KV.of("transform", "timer3"), Mockito.mock(FnDataReceiver.class)).build());
    when(stageBundleFactory.getBundle(any(), any(), any(), any(), any(), any())).thenReturn(bundle);
    testHarness.open();
    assertThat(operator.getCurrentOutputWatermark(), is(BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis()));
    // No bundle has been started, watermark can be freely advanced
    testHarness.processWatermark(0);
    assertThat(operator.getCurrentOutputWatermark(), is(0L));
    // Trigger a new bundle
    IntervalWindow intervalWindow = new IntervalWindow(new Instant(0), new Instant(9));
    WindowedValue<KV<String, Integer>> windowedValue = WindowedValue.of(KV.of("one", 1), Instant.now(), intervalWindow, PaneInfo.NO_FIRING);
    testHarness.processElement(new StreamRecord<>(windowedValue));
    // The output watermark should be held back during the bundle
    testHarness.processWatermark(1);
    assertThat(operator.getEffectiveInputWatermark(), is(1L));
    assertThat(operator.getCurrentOutputWatermark(), is(0L));
    // After the bundle has been finished, the watermark should be advanced
    operator.invokeFinishBundle();
    assertThat(operator.getCurrentOutputWatermark(), is(1L));
    // Bundle finished, watermark can be freely advanced
    testHarness.processWatermark(2);
    assertThat(operator.getEffectiveInputWatermark(), is(2L));
    assertThat(operator.getCurrentOutputWatermark(), is(2L));
    // Trigger a new bundle
    testHarness.processElement(new StreamRecord<>(windowedValue));
    // cleanup timer
    assertThat(testHarness.numEventTimeTimers(), is(1));
    // Set at timer
    Instant timerTarget = new Instant(5);
    Instant timerTarget2 = new Instant(6);
    operator.getLockToAcquireForStateAccessDuringBundles().lock();
    BiConsumer<String, Instant> timerConsumer = (timerId, timestamp) -> operator.setTimer(Timer.of(windowedValue.getValue().getKey(), "", windowedValue.getWindows(), timestamp, timestamp, PaneInfo.NO_FIRING), TimerInternals.TimerData.of("", TimerReceiverFactory.encodeToTimerDataTimerId("transform", timerId), StateNamespaces.window(IntervalWindow.getCoder(), intervalWindow), timestamp, timestamp, TimeDomain.EVENT_TIME));
    timerConsumer.accept("timer", timerTarget);
    timerConsumer.accept("timer2", timerTarget2);
    assertThat(testHarness.numEventTimeTimers(), is(3));
    // Advance input watermark past the timer
    // Check the output watermark is held back
    long targetWatermark = timerTarget.getMillis() + 100;
    testHarness.processWatermark(targetWatermark);
    // Do not yet advance the output watermark because we are still processing a bundle
    assertThat(testHarness.numEventTimeTimers(), is(3));
    assertThat(operator.getCurrentOutputWatermark(), is(2L));
    // Check that the timers are fired but the output watermark is advanced no further than
    // the minimum timer timestamp of the previous bundle because we are still processing a
    // bundle which might contain more timers.
    // Timers can create loops if they keep rescheduling themselves when firing
    // Thus, we advance the watermark asynchronously to allow for checkpointing to run
    operator.invokeFinishBundle();
    assertThat(testHarness.numEventTimeTimers(), is(3));
    testHarness.setProcessingTime(testHarness.getProcessingTime() + 1);
    assertThat(testHarness.numEventTimeTimers(), is(0));
    assertThat(operator.getCurrentOutputWatermark(), is(5L));
    // Output watermark is advanced synchronously when the bundle finishes,
    // no more timers are scheduled
    operator.invokeFinishBundle();
    assertThat(operator.getCurrentOutputWatermark(), is(targetWatermark));
    assertThat(testHarness.numEventTimeTimers(), is(0));
    // Watermark is advanced in a blocking fashion on close, not via a timers
    // Create a bundle with a pending timer to simulate that
    testHarness.processElement(new StreamRecord<>(windowedValue));
    timerConsumer.accept("timer3", new Instant(targetWatermark));
    assertThat(testHarness.numEventTimeTimers(), is(1));
    // This should be blocking until the watermark reaches Long.MAX_VALUE.
    testHarness.close();
    assertThat(testHarness.numEventTimeTimers(), is(0));
    assertThat(operator.getCurrentOutputWatermark(), is(Long.MAX_VALUE));
}
Also used : Arrays(java.util.Arrays) RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext) InMemoryStateInternals(org.apache.beam.runners.core.InMemoryStateInternals) FlinkExecutableStageContextFactory(org.apache.beam.runners.flink.translation.functions.FlinkExecutableStageContextFactory) CoderUtils(org.apache.beam.sdk.util.CoderUtils) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) KeyedOneInputStreamOperatorTestHarness(org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness) TimerInternals(org.apache.beam.runners.core.TimerInternals) OneInputStreamOperatorTestHarness(org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness) Mockito.doThrow(org.mockito.Mockito.doThrow) MockitoAnnotations(org.mockito.MockitoAnnotations) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) GlobalWindow(org.apache.beam.sdk.transforms.windowing.GlobalWindow) Components(org.apache.beam.model.pipeline.v1.RunnerApi.Components) CoderTypeInformation(org.apache.beam.runners.flink.translation.types.CoderTypeInformation) KvCoder(org.apache.beam.sdk.coders.KvCoder) StageBundleFactory(org.apache.beam.runners.fnexecution.control.StageBundleFactory) PAR_DO_TRANSFORM_URN(org.apache.beam.runners.core.construction.PTransformTranslation.PAR_DO_TRANSFORM_URN) FnDataReceiver(org.apache.beam.sdk.fn.data.FnDataReceiver) BundleProgressHandler(org.apache.beam.runners.fnexecution.control.BundleProgressHandler) SerializationUtils(org.apache.beam.repackaged.core.org.apache.commons.lang3.SerializationUtils) Struct(org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.Struct) OutputTag(org.apache.flink.util.OutputTag) BeamFnApi(org.apache.beam.model.fnexecution.v1.BeamFnApi) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Matchers.any(org.mockito.Matchers.any) Matchers.is(org.hamcrest.Matchers.is) StatefulDoFnRunner(org.apache.beam.runners.core.StatefulDoFnRunner) KV(org.apache.beam.sdk.values.KV) Mock(org.mockito.Mock) Duration(org.joda.time.Duration) RunWith(org.junit.runner.RunWith) ExecutableStagePayload(org.apache.beam.model.pipeline.v1.RunnerApi.ExecutableStagePayload) StateTags(org.apache.beam.runners.core.StateTags) PCollection(org.apache.beam.model.pipeline.v1.RunnerApi.PCollection) TupleTag(org.apache.beam.sdk.values.TupleTag) BiConsumer(java.util.function.BiConsumer) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) StateRequestHandler(org.apache.beam.runners.fnexecution.state.StateRequestHandler) Before(org.junit.Before) RunnerApi(org.apache.beam.model.pipeline.v1.RunnerApi) OutputReceiverFactory(org.apache.beam.runners.fnexecution.control.OutputReceiverFactory) StateRequestHandlers(org.apache.beam.runners.fnexecution.state.StateRequestHandlers) Test(org.junit.Test) BundleCheckpointHandler(org.apache.beam.runners.fnexecution.control.BundleCheckpointHandler) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) NoopLock(org.apache.beam.sdk.util.NoopLock) Lock(java.util.concurrent.locks.Lock) InMemoryTimerInternals(org.apache.beam.runners.core.InMemoryTimerInternals) Timer(org.apache.beam.runners.core.construction.Timer) BoundedWindow(org.apache.beam.sdk.transforms.windowing.BoundedWindow) VarIntCoder(org.apache.beam.sdk.coders.VarIntCoder) VoidCoder(org.apache.beam.sdk.coders.VoidCoder) IntervalWindow(org.apache.beam.sdk.transforms.windowing.IntervalWindow) TimeDomain(org.apache.beam.sdk.state.TimeDomain) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) StateNamespace(org.apache.beam.runners.core.StateNamespace) SerializablePipelineOptions(org.apache.beam.runners.core.construction.SerializablePipelineOptions) WindowedValue(org.apache.beam.sdk.util.WindowedValue) StreamRecordStripper.stripStreamRecordFromWindowedValue(org.apache.beam.runners.flink.translation.wrappers.streaming.StreamRecordStripper.stripStreamRecordFromWindowedValue) IsIterableContainingInOrder.contains(org.hamcrest.collection.IsIterableContainingInOrder.contains) FlinkPipelineOptions(org.apache.beam.runners.flink.FlinkPipelineOptions) ByteBuffer(java.nio.ByteBuffer) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Iterables(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables) BundleFinalizationHandler(org.apache.beam.runners.fnexecution.control.BundleFinalizationHandler) JobInfo(org.apache.beam.runners.fnexecution.provisioning.JobInfo) TypeInformation(org.apache.flink.api.common.typeinfo.TypeInformation) TimerReceiverFactory(org.apache.beam.runners.fnexecution.control.TimerReceiverFactory) PaneInfo(org.apache.beam.sdk.transforms.windowing.PaneInfo) Collection(java.util.Collection) DistributedCache(org.apache.flink.api.common.cache.DistributedCache) List(java.util.List) InstructionRequestHandler(org.apache.beam.runners.fnexecution.control.InstructionRequestHandler) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) WindowingStrategy(org.apache.beam.sdk.values.WindowingStrategy) Whitebox(org.powermock.reflect.Whitebox) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Coder(org.apache.beam.sdk.coders.Coder) Watermark(org.apache.flink.streaming.api.watermark.Watermark) HashMap(java.util.HashMap) MutableObject(org.apache.beam.repackaged.core.org.apache.commons.lang3.mutable.MutableObject) StateNamespaces(org.apache.beam.runners.core.StateNamespaces) StringUtf8Coder(org.apache.beam.sdk.coders.StringUtf8Coder) RemoteBundle(org.apache.beam.runners.fnexecution.control.RemoteBundle) StreamRecord(org.apache.flink.streaming.runtime.streamrecord.StreamRecord) ByteString(org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString) ExpectedException(org.junit.rules.ExpectedException) Nullable(org.checkerframework.checker.nullness.qual.Nullable) DoFnRunnerWithMetricsUpdate(org.apache.beam.runners.flink.metrics.DoFnRunnerWithMetricsUpdate) ProcessBundleDescriptors(org.apache.beam.runners.fnexecution.control.ProcessBundleDescriptors) ByteStringCoder(org.apache.beam.runners.fnexecution.wire.ByteStringCoder) Assert.assertNotNull(org.junit.Assert.assertNotNull) Charsets(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Charsets) FixedWindows(org.apache.beam.sdk.transforms.windowing.FixedWindows) Mockito.when(org.mockito.Mockito.when) JUnit4(org.junit.runners.JUnit4) KeyedStateBackend(org.apache.flink.runtime.state.KeyedStateBackend) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) BagState(org.apache.beam.sdk.state.BagState) Rule(org.junit.Rule) Instant(org.joda.time.Instant) Collections(java.util.Collections) FlinkStateInternalsTest(org.apache.beam.runners.flink.streaming.FlinkStateInternalsTest) ExecutableStageContext(org.apache.beam.runners.fnexecution.control.ExecutableStageContext) FnDataReceiver(org.apache.beam.sdk.fn.data.FnDataReceiver) Instant(org.joda.time.Instant) TupleTag(org.apache.beam.sdk.values.TupleTag) KV(org.apache.beam.sdk.values.KV) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ByteString(org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString) KeyedOneInputStreamOperatorTestHarness(org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness) WindowedValue(org.apache.beam.sdk.util.WindowedValue) StreamRecordStripper.stripStreamRecordFromWindowedValue(org.apache.beam.runners.flink.translation.wrappers.streaming.StreamRecordStripper.stripStreamRecordFromWindowedValue) SerializablePipelineOptions(org.apache.beam.runners.core.construction.SerializablePipelineOptions) RemoteBundle(org.apache.beam.runners.fnexecution.control.RemoteBundle) IntervalWindow(org.apache.beam.sdk.transforms.windowing.IntervalWindow) Test(org.junit.Test) FlinkStateInternalsTest(org.apache.beam.runners.flink.streaming.FlinkStateInternalsTest)

Example 77 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast by hazelcast.

the class DistributedObjectCounterCollector method forEachMetric.

@Override
public void forEachMetric(Node node, BiConsumer<PhoneHomeMetrics, String> metricsConsumer) {
    InternalProxyService proxyService = node.nodeEngine.getProxyService();
    Map<String, Long> objectsPerService = proxyService.getAllDistributedObjects().stream().filter(obj -> INTERNAL_OBJECTS_PREFIXES.stream().noneMatch(prefix -> obj.getName().startsWith(prefix))).filter(obj -> SERVICE_NAME_TO_METRIC_NAME.containsKey(obj.getServiceName())).collect(groupingBy(DistributedObject::getServiceName, Collectors.counting()));
    SERVICE_NAME_TO_METRIC_NAME.forEach((serviceName, metricNames) -> {
        metricsConsumer.accept(metricNames[0], String.valueOf(objectsPerService.getOrDefault(serviceName, 0L)));
        metricsConsumer.accept(metricNames[1], String.valueOf(proxyService.getCreatedCount(serviceName)));
    });
}
Also used : COUNT_OF_RING_BUFFERS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_RING_BUFFERS) INTERNAL_OBJECTS_PREFIXES(com.hazelcast.spi.impl.proxyservice.impl.ProxyRegistry.INTERNAL_OBJECTS_PREFIXES) COUNT_OF_MULTIMAPS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_MULTIMAPS_ALL_TIME) COUNT_OF_REPLICATED_MAPS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_REPLICATED_MAPS) COUNT_OF_SETS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_SETS_ALL_TIME) COUNT_OF_TOPICS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_TOPICS) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) QueueService(com.hazelcast.collection.impl.queue.QueueService) COUNT_OF_CARDINALITY_ESTIMATORS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_CARDINALITY_ESTIMATORS) COUNT_OF_CARDINALITY_ESTIMATORS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_CARDINALITY_ESTIMATORS_ALL_TIME) SetService(com.hazelcast.collection.impl.set.SetService) MultiMapService(com.hazelcast.multimap.impl.MultiMapService) COUNT_OF_QUEUES_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_QUEUES_ALL_TIME) MapUtil(com.hazelcast.internal.util.MapUtil) COUNT_OF_TOPICS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_TOPICS_ALL_TIME) ListService(com.hazelcast.collection.impl.list.ListService) CacheService(com.hazelcast.cache.impl.CacheService) InternalProxyService(com.hazelcast.spi.impl.proxyservice.InternalProxyService) Map(java.util.Map) COUNT_OF_REPLICATED_MAPS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_REPLICATED_MAPS_ALL_TIME) BiConsumer(java.util.function.BiConsumer) CardinalityEstimatorService(com.hazelcast.cardinality.impl.CardinalityEstimatorService) RingbufferService(com.hazelcast.ringbuffer.impl.RingbufferService) COUNT_OF_MAPS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_MAPS_ALL_TIME) COUNT_OF_LISTS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_LISTS) COUNT_OF_PN_COUNTERS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_PN_COUNTERS_ALL_TIME) COUNT_OF_LISTS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_LISTS_ALL_TIME) COUNT_OF_MULTIMAPS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_MULTIMAPS) COUNT_OF_RING_BUFFERS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_RING_BUFFERS_ALL_TIME) MapService(com.hazelcast.map.impl.MapService) FlakeIdGeneratorService(com.hazelcast.flakeidgen.impl.FlakeIdGeneratorService) TopicService(com.hazelcast.topic.impl.TopicService) PNCounterService(com.hazelcast.internal.crdt.pncounter.PNCounterService) Collectors(java.util.stream.Collectors) Node(com.hazelcast.instance.impl.Node) ReplicatedMapService(com.hazelcast.replicatedmap.impl.ReplicatedMapService) COUNT_OF_CACHES(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_CACHES) DistributedObject(com.hazelcast.core.DistributedObject) COUNT_OF_MAPS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_MAPS) COUNT_OF_SETS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_SETS) COUNT_OF_FLAKE_ID_GENERATORS_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_FLAKE_ID_GENERATORS_ALL_TIME) COUNT_OF_QUEUES(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_QUEUES) COUNT_OF_PN_COUNTERS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_PN_COUNTERS) COUNT_OF_CACHES_ALL_TIME(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_CACHES_ALL_TIME) COUNT_OF_FLAKE_ID_GENERATORS(com.hazelcast.internal.util.phonehome.PhoneHomeMetrics.COUNT_OF_FLAKE_ID_GENERATORS) InternalProxyService(com.hazelcast.spi.impl.proxyservice.InternalProxyService)

Example 78 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast by hazelcast.

the class MasterContext method invokeOnParticipant.

private void invokeOnParticipant(MemberInfo memberInfo, Supplier<Operation> operationSupplier, @Nullable Consumer<Collection<Map.Entry<MemberInfo, Object>>> completionCallback, @Nullable BiConsumer<Address, Object> individualCallback, boolean retryOnTimeoutException, ConcurrentMap<MemberInfo, Object> collectedResponses, AtomicInteger remainingCount) {
    Operation operation = operationSupplier.get();
    InternalCompletableFuture<Object> future = nodeEngine.getOperationService().createInvocationBuilder(JetServiceBackend.SERVICE_NAME, operation, memberInfo.getAddress()).invoke();
    future.whenCompleteAsync(withTryCatch(logger, (r, throwable) -> {
        Object response = r != null ? r : throwable != null ? peel(throwable) : NULL_OBJECT;
        if (retryOnTimeoutException && throwable instanceof OperationTimeoutException) {
            logger.warning("Retrying " + operation.getClass().getName() + " that failed with " + OperationTimeoutException.class.getSimpleName() + " in " + jobIdString());
            invokeOnParticipant(memberInfo, operationSupplier, completionCallback, individualCallback, retryOnTimeoutException, collectedResponses, remainingCount);
            return;
        }
        if (individualCallback != null) {
            individualCallback.accept(memberInfo.getAddress(), throwable != null ? peel(throwable) : r);
        }
        Object oldResponse = collectedResponses.put(memberInfo, response);
        assert oldResponse == null : "Duplicate response for " + memberInfo.getAddress() + ". Old=" + oldResponse + ", new=" + response;
        if (remainingCount.decrementAndGet() == 0 && completionCallback != null) {
            completionCallback.accept(collectedResponses.entrySet().stream().map(e -> e.getValue() == NULL_OBJECT ? entry(e.getKey(), null) : e).collect(Collectors.toList()));
        }
    }));
}
Also used : Address(com.hazelcast.cluster.Address) NOT_RUNNING(com.hazelcast.jet.core.JobStatus.NOT_RUNNING) CompletableFuture(java.util.concurrent.CompletableFuture) StartExecutionOperation(com.hazelcast.jet.impl.operation.StartExecutionOperation) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) InternalCompletableFuture(com.hazelcast.spi.impl.InternalCompletableFuture) Util.jobNameAndExecutionId(com.hazelcast.jet.impl.util.Util.jobNameAndExecutionId) ILogger(com.hazelcast.logging.ILogger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Operation(com.hazelcast.spi.impl.operationservice.Operation) Util.entry(com.hazelcast.jet.Util.entry) ExceptionUtil.withTryCatch(com.hazelcast.jet.impl.util.ExceptionUtil.withTryCatch) MemberInfo(com.hazelcast.internal.cluster.MemberInfo) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) SUSPENDED(com.hazelcast.jet.core.JobStatus.SUSPENDED) JobStatus(com.hazelcast.jet.core.JobStatus) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) NodeEngineImpl(com.hazelcast.spi.impl.NodeEngineImpl) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Collectors.toConcurrentMap(java.util.stream.Collectors.toConcurrentMap) Collection(java.util.Collection) JobConfig(com.hazelcast.jet.config.JobConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) Util.idToString(com.hazelcast.jet.Util.idToString) ExceptionUtil.peel(com.hazelcast.jet.impl.util.ExceptionUtil.peel) ExecutionPlan(com.hazelcast.jet.impl.execution.init.ExecutionPlan) OperationTimeoutException(com.hazelcast.core.OperationTimeoutException) Entry(java.util.Map.Entry) OperationTimeoutException(com.hazelcast.core.OperationTimeoutException) StartExecutionOperation(com.hazelcast.jet.impl.operation.StartExecutionOperation) Operation(com.hazelcast.spi.impl.operationservice.Operation)

Example 79 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast by hazelcast.

the class MapProxySupport method putAllInternal.

/**
 * This method will group all entries per partition and send one operation
 * per member. If there are e.g. five keys for a single member, even if
 * they are from different partitions, there will only be a single remote
 * invocation instead of five.
 * <p>
 * There is also an optional support for batching to send smaller packages.
 * Takes care about {@code null} checks for keys and values.
 *
 * @param future iff not-null, execute asynchronously by completing this future.
 *               Batching is not supported in async mode
 */
@SuppressWarnings({ "checkstyle:MethodLength", "checkstyle:CyclomaticComplexity", "checkstyle:NPathComplexity" })
protected void putAllInternal(Map<? extends K, ? extends V> map, @Nullable InternalCompletableFuture<Void> future, boolean triggerMapLoader) {
    try {
        int mapSize = map.size();
        if (mapSize == 0) {
            if (future != null) {
                future.complete(null);
            }
            return;
        }
        boolean useBatching = future == null && isPutAllUseBatching(mapSize);
        int partitionCount = partitionService.getPartitionCount();
        int initialSize = getPutAllInitialSize(useBatching, mapSize, partitionCount);
        Map<Address, List<Integer>> memberPartitionsMap = partitionService.getMemberPartitionsMap();
        // init counters for batching
        MutableLong[] counterPerMember = null;
        Address[] addresses = null;
        if (useBatching) {
            counterPerMember = new MutableLong[partitionCount];
            addresses = new Address[partitionCount];
            for (Entry<Address, List<Integer>> addressListEntry : memberPartitionsMap.entrySet()) {
                MutableLong counter = new MutableLong();
                Address address = addressListEntry.getKey();
                for (int partitionId : addressListEntry.getValue()) {
                    counterPerMember[partitionId] = counter;
                    addresses[partitionId] = address;
                }
            }
        }
        // fill entriesPerPartition
        MapEntries[] entriesPerPartition = new MapEntries[partitionCount];
        for (Entry entry : map.entrySet()) {
            checkNotNull(entry.getKey(), NULL_KEY_IS_NOT_ALLOWED);
            checkNotNull(entry.getValue(), NULL_VALUE_IS_NOT_ALLOWED);
            Data keyData = toDataWithStrategy(entry.getKey());
            int partitionId = partitionService.getPartitionId(keyData);
            MapEntries entries = entriesPerPartition[partitionId];
            if (entries == null) {
                entries = new MapEntries(initialSize);
                entriesPerPartition[partitionId] = entries;
            }
            entries.add(keyData, toData(entry.getValue()));
            if (useBatching) {
                long currentSize = ++counterPerMember[partitionId].value;
                if (currentSize % putAllBatchSize == 0) {
                    List<Integer> partitions = memberPartitionsMap.get(addresses[partitionId]);
                    invokePutAllOperation(addresses[partitionId], partitions, entriesPerPartition, triggerMapLoader).get();
                }
            }
        }
        // invoke operations for entriesPerPartition
        AtomicInteger counter = new AtomicInteger(memberPartitionsMap.size());
        InternalCompletableFuture<Void> resultFuture = future != null ? future : new InternalCompletableFuture<>();
        BiConsumer<Void, Throwable> callback = (response, t) -> {
            if (t != null) {
                resultFuture.completeExceptionally(t);
            }
            if (counter.decrementAndGet() == 0) {
                try {
                    // don't ignore errors here, see https://github.com/hazelcast/hazelcast-jet/issues/3046
                    finalizePutAll(map);
                } catch (Throwable e) {
                    resultFuture.completeExceptionally(e);
                    return;
                }
                if (!resultFuture.isDone()) {
                    resultFuture.complete(null);
                }
            }
        };
        for (Entry<Address, List<Integer>> entry : memberPartitionsMap.entrySet()) {
            invokePutAllOperation(entry.getKey(), entry.getValue(), entriesPerPartition, triggerMapLoader).whenCompleteAsync(callback);
        }
        // if executing in sync mode, block for the responses
        if (future == null) {
            resultFuture.get();
        }
    } catch (Throwable e) {
        throw rethrow(e);
    }
}
Also used : MutableLong(com.hazelcast.internal.util.MutableLong) Arrays(java.util.Arrays) PartitionPredicate(com.hazelcast.query.PartitionPredicate) ExceptionUtil.rethrow(com.hazelcast.internal.util.ExceptionUtil.rethrow) AbstractDistributedObject(com.hazelcast.spi.impl.AbstractDistributedObject) Collections.singletonList(java.util.Collections.singletonList) MapConfig(com.hazelcast.config.MapConfig) Future(java.util.concurrent.Future) MapEntries(com.hazelcast.map.impl.MapEntries) TruePredicate(com.hazelcast.query.impl.predicates.TruePredicate) SerializationService(com.hazelcast.internal.serialization.SerializationService) PartitionContainer(com.hazelcast.map.impl.PartitionContainer) Map(java.util.Map) LockSupportServiceImpl(com.hazelcast.internal.locksupport.LockSupportServiceImpl) PartitioningStrategy(com.hazelcast.partition.PartitioningStrategy) IPartitionService(com.hazelcast.internal.partition.IPartitionService) ExceptionUtil(com.hazelcast.internal.util.ExceptionUtil) Set(java.util.Set) EntryView(com.hazelcast.core.EntryView) Result(com.hazelcast.map.impl.query.Result) QueryCacheContext(com.hazelcast.map.impl.querycache.QueryCacheContext) Predicates.alwaysFalse(com.hazelcast.query.Predicates.alwaysFalse) AddIndexOperation(com.hazelcast.map.impl.operation.AddIndexOperation) Target(com.hazelcast.map.impl.query.Target) IterableUtil.nullToEmpty(com.hazelcast.internal.util.IterableUtil.nullToEmpty) IPartition(com.hazelcast.internal.partition.IPartition) EventListener(java.util.EventListener) AwaitMapFlushOperation(com.hazelcast.map.impl.operation.AwaitMapFlushOperation) MapOperationProvider(com.hazelcast.map.impl.operation.MapOperationProvider) MapStoreConfig(com.hazelcast.config.MapStoreConfig) LockProxySupport(com.hazelcast.internal.locksupport.LockProxySupport) IterationType(com.hazelcast.internal.util.IterationType) PartitionIdSet(com.hazelcast.internal.util.collection.PartitionIdSet) QueryEngine(com.hazelcast.map.impl.query.QueryEngine) HazelcastInstanceAware(com.hazelcast.core.HazelcastInstanceAware) Query(com.hazelcast.map.impl.query.Query) EntryEventFilter(com.hazelcast.map.impl.EntryEventFilter) Math.log10(java.lang.Math.log10) InMemoryFormat(com.hazelcast.config.InMemoryFormat) Supplier(java.util.function.Supplier) CLEAR_ALL(com.hazelcast.core.EntryEventType.CLEAR_ALL) RemoveInterceptorOperationSupplier(com.hazelcast.map.impl.operation.RemoveInterceptorOperationSupplier) ArrayList(java.util.ArrayList) QueryEventFilter(com.hazelcast.map.impl.query.QueryEventFilter) EntryListenerConfig(com.hazelcast.config.EntryListenerConfig) BiConsumer(java.util.function.BiConsumer) BinaryOperationFactory(com.hazelcast.spi.impl.operationservice.BinaryOperationFactory) Nullable(javax.annotation.Nullable) LocalMapStats(com.hazelcast.map.LocalMapStats) InvocationUtil.invokeOnStableClusterSerial(com.hazelcast.internal.util.InvocationUtil.invokeOnStableClusterSerial) ThreadUtil.getThreadId(com.hazelcast.internal.util.ThreadUtil.getThreadId) InternalCompletableFuture.newCompletedFuture(com.hazelcast.spi.impl.InternalCompletableFuture.newCompletedFuture) IsPartitionLoadedOperationFactory(com.hazelcast.map.impl.operation.IsPartitionLoadedOperationFactory) ClassLoaderUtil(com.hazelcast.internal.nio.ClassLoaderUtil) TargetMode(com.hazelcast.map.impl.query.Target.TargetMode) QueryCacheEndToEndProvider(com.hazelcast.map.impl.querycache.subscriber.QueryCacheEndToEndProvider) CollectionUtil.asIntegerList(com.hazelcast.internal.util.CollectionUtil.asIntegerList) EventFilter(com.hazelcast.spi.impl.eventservice.EventFilter) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) Target.createPartitionTarget(com.hazelcast.map.impl.query.Target.createPartitionTarget) LocalMapStatsImpl(com.hazelcast.internal.monitor.impl.LocalMapStatsImpl) MapEventPublisher(com.hazelcast.map.impl.event.MapEventPublisher) MapPartitionLostListenerConfig(com.hazelcast.config.MapPartitionLostListenerConfig) EntryProcessor(com.hazelcast.map.EntryProcessor) ReadOnly(com.hazelcast.core.ReadOnly) AddInterceptorOperationSupplier(com.hazelcast.map.impl.operation.AddInterceptorOperationSupplier) OperationFactory(com.hazelcast.spi.impl.operationservice.OperationFactory) OperationService(com.hazelcast.spi.impl.operationservice.OperationService) Address(com.hazelcast.cluster.Address) InvocationFuture(com.hazelcast.spi.impl.operationservice.impl.InvocationFuture) InternalCompletableFuture(com.hazelcast.spi.impl.InternalCompletableFuture) IsEmptyOperationFactory(com.hazelcast.map.impl.operation.IsEmptyOperationFactory) MapListener(com.hazelcast.map.listener.MapListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InitializingObject(com.hazelcast.spi.impl.InitializingObject) IndexUtils(com.hazelcast.query.impl.IndexUtils) Predicate(com.hazelcast.query.Predicate) CALLER_RUNS(com.hazelcast.internal.util.ConcurrencyUtil.CALLER_RUNS) Collection(java.util.Collection) IsKeyLoadFinishedOperation(com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation) UUID(java.util.UUID) Math.ceil(java.lang.Math.ceil) Math.min(java.lang.Math.min) SubscriberContext(com.hazelcast.map.impl.querycache.subscriber.SubscriberContext) IndexConfig(com.hazelcast.config.IndexConfig) List(java.util.List) Preconditions.checkFalse(com.hazelcast.internal.util.Preconditions.checkFalse) SetUtil.createHashSet(com.hazelcast.internal.util.SetUtil.createHashSet) TimeUtil.timeInMsOrOneIfResultIsZero(com.hazelcast.internal.util.TimeUtil.timeInMsOrOneIfResultIsZero) Projection(com.hazelcast.projection.Projection) IterableUtil(com.hazelcast.internal.util.IterableUtil) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) MapUtil.createHashMap(com.hazelcast.internal.util.MapUtil.createHashMap) Aggregator(com.hazelcast.aggregation.Aggregator) ListenerConfig(com.hazelcast.config.ListenerConfig) IndexType(com.hazelcast.config.IndexType) Operation(com.hazelcast.spi.impl.operationservice.Operation) HazelcastProperty(com.hazelcast.spi.properties.HazelcastProperty) Collections.singletonMap(java.util.Collections.singletonMap) MapUtil.toIntSize(com.hazelcast.internal.util.MapUtil.toIntSize) Nonnull(javax.annotation.Nonnull) Timer(com.hazelcast.internal.util.Timer) NodeEngine(com.hazelcast.spi.impl.NodeEngine) Iterator(java.util.Iterator) EntryEventType(com.hazelcast.core.EntryEventType) MapOperation(com.hazelcast.map.impl.operation.MapOperation) MapInterceptor(com.hazelcast.map.MapInterceptor) HazelcastProperties(com.hazelcast.spi.properties.HazelcastProperties) Data(com.hazelcast.internal.serialization.Data) MapService(com.hazelcast.map.impl.MapService) MapServiceContext(com.hazelcast.map.impl.MapServiceContext) RecordStore(com.hazelcast.map.impl.recordstore.RecordStore) TimeUnit(java.util.concurrent.TimeUnit) SERVICE_NAME(com.hazelcast.map.impl.MapService.SERVICE_NAME) MapPartitionLostListener(com.hazelcast.map.listener.MapPartitionLostListener) ENTRY_REMOVING_PROCESSOR(com.hazelcast.map.impl.EntryRemovingProcessor.ENTRY_REMOVING_PROCESSOR) Collections(java.util.Collections) IMap(com.hazelcast.map.IMap) Address(com.hazelcast.cluster.Address) Data(com.hazelcast.internal.serialization.Data) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableLong(com.hazelcast.internal.util.MutableLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MapEntries(com.hazelcast.map.impl.MapEntries) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) CollectionUtil.asIntegerList(com.hazelcast.internal.util.CollectionUtil.asIntegerList) List(java.util.List)

Example 80 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast by hazelcast.

the class MultiMapProxySupport method putAllInternal.

// NB: this method is generally copied from MapProxySupport#putAllInternal
@SuppressWarnings({ "checkstyle:npathcomplexity", "checkstyle:methodlength" })
protected void putAllInternal(Map<Data, Data> map, @Nullable InternalCompletableFuture<Void> future) {
    // get partition to entries mapping
    try {
        int mapSize = map.size();
        if (mapSize == 0) {
            if (future != null) {
                future.complete(null);
            }
            return;
        }
        int partitionCount = partitionService.getPartitionCount();
        int initialSize = getPutAllInitialSize(mapSize, partitionCount);
        // get node to partition mapping
        Map<Address, List<Integer>> memberPartitionsMap = partitionService.getMemberPartitionsMap();
        // fill entriesPerPartition
        MapEntries[] entriesPerPartition = new MapEntries[partitionCount];
        for (Map.Entry<Data, Data> entry : map.entrySet()) {
            checkNotNull(entry.getKey(), NULL_KEY_IS_NOT_ALLOWED);
            checkNotNull(entry.getValue(), NULL_VALUE_IS_NOT_ALLOWED);
            Data keyData = entry.getKey();
            int partitionId = partitionService.getPartitionId(keyData);
            MapEntries entries = entriesPerPartition[partitionId];
            if (entries == null) {
                entries = new MapEntries(initialSize);
                entriesPerPartition[partitionId] = entries;
            }
            entries.add(keyData, entry.getValue());
        }
        // invoke operations for entriesPerPartition
        AtomicInteger counter = new AtomicInteger(memberPartitionsMap.size());
        InternalCompletableFuture<Void> resultFuture = future != null ? future : new InternalCompletableFuture<>();
        BiConsumer<Void, Throwable> callback = (response, t) -> {
            if (t != null) {
                resultFuture.completeExceptionally(t);
            }
            if (counter.decrementAndGet() == 0) {
                if (!resultFuture.isDone()) {
                    resultFuture.complete(null);
                }
            }
        };
        for (Map.Entry<Address, List<Integer>> entry : memberPartitionsMap.entrySet()) {
            invokePutAllOperation(entry.getKey(), entry.getValue(), entriesPerPartition).whenCompleteAsync(callback);
        }
        // if executing in sync mode, block for the responses
        if (future == null) {
            resultFuture.get();
        }
    } catch (Throwable e) {
        throw rethrow(e);
    }
}
Also used : Address(com.hazelcast.cluster.Address) Arrays(java.util.Arrays) CompletableFuture(java.util.concurrent.CompletableFuture) ExceptionUtil.rethrow(com.hazelcast.internal.util.ExceptionUtil.rethrow) AbstractDistributedObject(com.hazelcast.spi.impl.AbstractDistributedObject) InternalCompletableFuture(com.hazelcast.spi.impl.InternalCompletableFuture) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) MultiMapConfig(com.hazelcast.config.MultiMapConfig) NULL_VALUE_IS_NOT_ALLOWED(com.hazelcast.multimap.impl.MultiMapProxyImpl.NULL_VALUE_IS_NOT_ALLOWED) MapEntries(com.hazelcast.map.impl.MapEntries) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PutOperation(com.hazelcast.multimap.impl.operations.PutOperation) Operation(com.hazelcast.spi.impl.operationservice.Operation) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) GetAllOperation(com.hazelcast.multimap.impl.operations.GetAllOperation) MultiMapOperationFactory(com.hazelcast.multimap.impl.operations.MultiMapOperationFactory) Collections.singletonMap(java.util.Collections.singletonMap) MapUtil.toIntSize(com.hazelcast.internal.util.MapUtil.toIntSize) MultiMapResponse(com.hazelcast.multimap.impl.operations.MultiMapResponse) OperationFactoryType(com.hazelcast.multimap.impl.operations.MultiMapOperationFactory.OperationFactoryType) LockSupportServiceImpl(com.hazelcast.internal.locksupport.LockSupportServiceImpl) Nullable(javax.annotation.Nullable) Timer(com.hazelcast.internal.util.Timer) CALLER_RUNS(com.hazelcast.internal.util.ConcurrencyUtil.CALLER_RUNS) RemoveOperation(com.hazelcast.multimap.impl.operations.RemoveOperation) InternalCompletableFuture.newCompletedFuture(com.hazelcast.spi.impl.InternalCompletableFuture.newCompletedFuture) NodeEngine(com.hazelcast.spi.impl.NodeEngine) EntryEventType(com.hazelcast.core.EntryEventType) IPartitionService(com.hazelcast.internal.partition.IPartitionService) DistributedObjectNamespace(com.hazelcast.internal.services.DistributedObjectNamespace) CollectionUtil.asIntegerList(com.hazelcast.internal.util.CollectionUtil.asIntegerList) Data(com.hazelcast.internal.serialization.Data) ExceptionUtil(com.hazelcast.internal.util.ExceptionUtil) Set(java.util.Set) LocalMultiMapStatsImpl(com.hazelcast.internal.monitor.impl.LocalMultiMapStatsImpl) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) DeleteOperation(com.hazelcast.multimap.impl.operations.DeleteOperation) MultiMapPutAllOperationFactory(com.hazelcast.multimap.impl.operations.MultiMapPutAllOperationFactory) RemoveAllOperation(com.hazelcast.multimap.impl.operations.RemoveAllOperation) List(java.util.List) LockProxySupport(com.hazelcast.internal.locksupport.LockProxySupport) OperationFactory(com.hazelcast.spi.impl.operationservice.OperationFactory) OperationService(com.hazelcast.spi.impl.operationservice.OperationService) NULL_KEY_IS_NOT_ALLOWED(com.hazelcast.multimap.impl.MultiMapProxyImpl.NULL_KEY_IS_NOT_ALLOWED) CountOperation(com.hazelcast.multimap.impl.operations.CountOperation) ThreadUtil(com.hazelcast.internal.util.ThreadUtil) Address(com.hazelcast.cluster.Address) Data(com.hazelcast.internal.serialization.Data) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MapEntries(com.hazelcast.map.impl.MapEntries) CollectionUtil.asIntegerList(com.hazelcast.internal.util.CollectionUtil.asIntegerList) List(java.util.List) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap)

Aggregations

BiConsumer (java.util.function.BiConsumer)255 Test (org.junit.Test)110 List (java.util.List)106 Map (java.util.Map)77 IOException (java.io.IOException)75 Consumer (java.util.function.Consumer)69 ArrayList (java.util.ArrayList)68 HashMap (java.util.HashMap)64 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)50 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Assert (org.junit.Assert)43 Function (java.util.function.Function)41 Optional (java.util.Optional)40 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35