Search in sources :

Example 51 with Operation

use of com.hazelcast.spi.impl.operationservice.Operation 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 52 with Operation

use of com.hazelcast.spi.impl.operationservice.Operation in project hazelcast by hazelcast.

the class MapProxySupport method clearInternal.

public void clearInternal() {
    try {
        Operation clearOperation = operationProvider.createClearOperation(name);
        clearOperation.setServiceName(SERVICE_NAME);
        BinaryOperationFactory factory = new BinaryOperationFactory(clearOperation, getNodeEngine());
        Map<Integer, Object> resultMap = operationService.invokeOnAllPartitions(SERVICE_NAME, factory);
        int clearedCount = 0;
        for (Object object : resultMap.values()) {
            clearedCount += (Integer) object;
        }
        if (clearedCount > 0) {
            publishMapEvent(clearedCount, CLEAR_ALL);
        }
        incrementOtherOperationsStat();
    } catch (Throwable t) {
        throw rethrow(t);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BinaryOperationFactory(com.hazelcast.spi.impl.operationservice.BinaryOperationFactory) AbstractDistributedObject(com.hazelcast.spi.impl.AbstractDistributedObject) InitializingObject(com.hazelcast.spi.impl.InitializingObject) AddIndexOperation(com.hazelcast.map.impl.operation.AddIndexOperation) AwaitMapFlushOperation(com.hazelcast.map.impl.operation.AwaitMapFlushOperation) IsKeyLoadFinishedOperation(com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation) Operation(com.hazelcast.spi.impl.operationservice.Operation) MapOperation(com.hazelcast.map.impl.operation.MapOperation)

Example 53 with Operation

use of com.hazelcast.spi.impl.operationservice.Operation in project hazelcast by hazelcast.

the class MapProxySupport method waitUntilLoaded.

public void waitUntilLoaded() {
    try {
        int mapNamesPartitionId = partitionService.getPartitionId(name);
        // first we have to check if key-load finished - otherwise
        // the loading on other partitions might not have started.
        // In this case we can't invoke IsPartitionLoadedOperation
        // -> they will return "true", but it won't be correct
        int sleepDurationMillis = INITIAL_WAIT_LOAD_SLEEP_MILLIS;
        while (true) {
            Operation op = new IsKeyLoadFinishedOperation(name);
            Future<Boolean> loadingFuture = operationService.invokeOnPartition(SERVICE_NAME, op, mapNamesPartitionId);
            if (loadingFuture.get()) {
                break;
            }
            // sleep with some back-off
            TimeUnit.MILLISECONDS.sleep(sleepDurationMillis);
            sleepDurationMillis = (sleepDurationMillis * 2 < MAXIMAL_WAIT_LOAD_SLEEP_MILLIS) ? sleepDurationMillis * 2 : MAXIMAL_WAIT_LOAD_SLEEP_MILLIS;
        }
        OperationFactory opFactory = new IsPartitionLoadedOperationFactory(name);
        Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, opFactory);
        // wait for all the data to be loaded on all partitions - wait forever
        waitAllTrue(results, opFactory);
    } catch (Throwable t) {
        throw rethrow(t);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IsKeyLoadFinishedOperation(com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation) IsPartitionLoadedOperationFactory(com.hazelcast.map.impl.operation.IsPartitionLoadedOperationFactory) AbstractDistributedObject(com.hazelcast.spi.impl.AbstractDistributedObject) InitializingObject(com.hazelcast.spi.impl.InitializingObject) AddIndexOperation(com.hazelcast.map.impl.operation.AddIndexOperation) AwaitMapFlushOperation(com.hazelcast.map.impl.operation.AwaitMapFlushOperation) IsKeyLoadFinishedOperation(com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation) Operation(com.hazelcast.spi.impl.operationservice.Operation) MapOperation(com.hazelcast.map.impl.operation.MapOperation) BinaryOperationFactory(com.hazelcast.spi.impl.operationservice.BinaryOperationFactory) IsPartitionLoadedOperationFactory(com.hazelcast.map.impl.operation.IsPartitionLoadedOperationFactory) OperationFactory(com.hazelcast.spi.impl.operationservice.OperationFactory) IsEmptyOperationFactory(com.hazelcast.map.impl.operation.IsEmptyOperationFactory)

Example 54 with Operation

use of com.hazelcast.spi.impl.operationservice.Operation in project hazelcast by hazelcast.

the class QueryEngineImpl method dispatchFullQueryOnLocalMemberOnQueryThread.

private List<Future<Result>> dispatchFullQueryOnLocalMemberOnQueryThread(Query query) {
    Operation operation = mapServiceContext.getMapOperationProvider(query.getMapName()).createQueryOperation(query);
    Future<Result> result = operationService.invokeOnTarget(MapService.SERVICE_NAME, operation, nodeEngine.getThisAddress());
    return singletonList(result);
}
Also used : Operation(com.hazelcast.spi.impl.operationservice.Operation)

Example 55 with Operation

use of com.hazelcast.spi.impl.operationservice.Operation in project hazelcast by hazelcast.

the class QueryEngineImpl method dispatchFullQueryOnAllMembersOnQueryThread.

private List<Future<Result>> dispatchFullQueryOnAllMembersOnQueryThread(Query query) {
    Collection<Address> members;
    if (query.getPartitionIdSet().size() == partitionService.getPartitionCount()) {
        members = clusterService.getMembers(DATA_MEMBER_SELECTOR).stream().map(m -> m.getAddress()).collect(Collectors.toList());
    } else {
        members = new HashSet<>();
        for (PrimitiveIterator.OfInt iterator = query.getPartitionIdSet().intIterator(); iterator.hasNext(); ) {
            members.add(partitionService.getPartitionOwnerOrWait(iterator.next()));
        }
    }
    List<Future<Result>> futures = new ArrayList<>(members.size());
    for (Address address : members) {
        Operation operation = createQueryOperation(query);
        Future<Result> future = operationService.invokeOnTarget(MapService.SERVICE_NAME, operation, address);
        futures.add(future);
    }
    return futures;
}
Also used : Address(com.hazelcast.cluster.Address) PrimitiveIterator(java.util.PrimitiveIterator) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) Operation(com.hazelcast.spi.impl.operationservice.Operation)

Aggregations

Operation (com.hazelcast.spi.impl.operationservice.Operation)271 Test (org.junit.Test)80 QuickTest (com.hazelcast.test.annotation.QuickTest)79 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)59 OperationService (com.hazelcast.spi.impl.operationservice.OperationService)56 Address (com.hazelcast.cluster.Address)31 HazelcastInstance (com.hazelcast.core.HazelcastInstance)25 Data (com.hazelcast.internal.serialization.Data)24 Future (java.util.concurrent.Future)24 Member (com.hazelcast.cluster.Member)22 ArrayList (java.util.ArrayList)21 NodeEngine (com.hazelcast.spi.impl.NodeEngine)18 NodeEngineImpl (com.hazelcast.spi.impl.NodeEngineImpl)17 TestHazelcastInstanceFactory (com.hazelcast.test.TestHazelcastInstanceFactory)17 AssertTask (com.hazelcast.test.AssertTask)15 ILogger (com.hazelcast.logging.ILogger)14 UrgentSystemOperation (com.hazelcast.spi.impl.operationservice.UrgentSystemOperation)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)13 Config (com.hazelcast.config.Config)12 CompletableFuture (java.util.concurrent.CompletableFuture)12