Example usage for java.util TreeSet forEach

List of usage examples for java.util TreeSet forEach

Introduction

In this page you can find the example usage for java.util TreeSet forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:com.evolveum.midpoint.wf.impl.processes.common.DumpVariables.java

private void dumpExecutionVariables(String executionId, DelegateExecution delegateExecution,
        Execution execution, Set<String> variablesSeen, RuntimeService runtimeService) {
    Map<String, Object> variablesLocal = runtimeService.getVariablesLocal(executionId);
    LOGGER.trace("Execution id={} ({} variables); class={}/{}", executionId, variablesLocal.size(),
            delegateExecution != null ? delegateExecution.getClass().getName() : null,
            execution != null ? execution.getClass().getName() : null);
    TreeSet<String> names = new TreeSet<>(variablesLocal.keySet());
    names.forEach(n -> LOGGER.trace(" - {} = {} {}", n, variablesLocal.get(n),
            variablesSeen.contains(n) ? "(dup)" : ""));
    variablesSeen.addAll(variablesLocal.keySet());
    if (delegateExecution instanceof ExecutionEntity) {
        ExecutionEntity executionEntity = (ExecutionEntity) delegateExecution;
        if (executionEntity.getParent() != null) {
            dumpExecutionVariables(executionEntity.getParentId(), executionEntity.getParent(), null,
                    variablesSeen, runtimeService);
        }/*  w  w  w . ja va  2  s.c om*/
    } else if (delegateExecution instanceof ExecutionImpl) {
        ExecutionImpl executionImpl = (ExecutionImpl) delegateExecution;
        if (executionImpl.getParent() != null) {
            dumpExecutionVariables(executionImpl.getParentId(), executionImpl.getParent(), null, variablesSeen,
                    runtimeService);
        }
    } else {
        Execution execution1 = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        if (execution1 == null) {
            LOGGER.trace("Execution with id {} was not found.", executionId);
        } else if (execution1.getParentId() != null) {
            Execution execution2 = runtimeService.createExecutionQuery().executionId(execution1.getParentId())
                    .singleResult();
            dumpExecutionVariables(execution.getParentId(), null, execution2, variablesSeen, runtimeService);
        }
    }
}

From source file:org.apache.bookkeeper.stream.storage.impl.sc.DefaultStorageContainerController.java

@Override
public ClusterAssignmentData computeIdealState(ClusterMetadata clusterMetadata,
        ClusterAssignmentData currentState, Set<BookieSocketAddress> currentCluster) {

    if (currentCluster.isEmpty()) {
        log.info("Current cluster is empty. No alive server is found.");
        return currentState;
    }/*  w  w  w  .j av  a 2  s  .  c o m*/

    // 1. get current server assignments
    Map<BookieSocketAddress, Set<Long>> currentServerAssignments;
    try {
        currentServerAssignments = currentState.getServersMap().entrySet().stream()
                .collect(Collectors.toMap(e1 -> {
                    try {
                        return new BookieSocketAddress(e1.getKey());
                    } catch (UnknownHostException uhe) {
                        log.error("Invalid cluster ");
                        throw new UncheckedExecutionException(
                                "Invalid server found in current assignment map" + e1.getKey(), uhe);
                    }
                }, e2 -> e2.getValue().getContainersList().stream().collect(Collectors.toSet())));
    } catch (UncheckedExecutionException uee) {
        log.warn("Invalid cluster assignment data is found : {} - {}. Recompute assignment from empty state",
                currentState, uee.getCause().getMessage());
        currentServerAssignments = Maps.newHashMap();
    }
    Set<BookieSocketAddress> currentServersAssigned = currentServerAssignments.keySet();

    // 2. if no servers is assigned, initialize the ideal state
    if (currentServersAssigned.isEmpty()) {
        return initializeIdealState(clusterMetadata, currentCluster);
    }

    // 3. get the cluster diffs
    Set<BookieSocketAddress> serversAdded = Sets.difference(currentCluster, currentServersAssigned)
            .immutableCopy();
    Set<BookieSocketAddress> serversRemoved = Sets.difference(currentServersAssigned, currentCluster)
            .immutableCopy();

    if (serversAdded.isEmpty() && serversRemoved.isEmpty()) {
        // cluster is unchanged, assuming the current state is ideal, no re-assignment is required.
        return currentState;
    }

    log.info(
            "Storage container controller detects cluster changed:\n"
                    + "\t {} servers added: {}\n\t {} servers removed: {}",
            serversAdded.size(), serversAdded, serversRemoved.size(), serversRemoved);

    // 4. compute the containers that owned by servers removed. these containers are needed to be reassigned.
    Set<Long> containersToReassign = currentServerAssignments.entrySet().stream()
            .filter(serverEntry -> !currentCluster.contains(serverEntry.getKey()))
            .flatMap(serverEntry -> serverEntry.getValue().stream()).collect(Collectors.toSet());

    // 5. use an ordered set as priority deque to sort the servers by the number of assigned containers
    TreeSet<Pair<BookieSocketAddress, LinkedList<Long>>> assignmentQueue = new TreeSet<>(
            new ServerAssignmentDataComparator());
    for (Map.Entry<BookieSocketAddress, Set<Long>> entry : currentServerAssignments.entrySet()) {
        BookieSocketAddress host = entry.getKey();

        if (!currentCluster.contains(host)) {
            if (log.isTraceEnabled()) {
                log.trace("Host {} is not in current cluster anymore", host);
            }
            continue;
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Adding host {} to assignment queue", host);
            }
            assignmentQueue.add(Pair.of(host, Lists.newLinkedList(entry.getValue())));
        }
    }

    // 6. add new servers
    for (BookieSocketAddress server : serversAdded) {
        assignmentQueue.add(Pair.of(server, Lists.newLinkedList()));
    }

    // 7. assign the containers that are needed to be reassigned.
    for (Long containerId : containersToReassign) {
        Pair<BookieSocketAddress, LinkedList<Long>> leastLoadedServer = assignmentQueue.pollFirst();
        leastLoadedServer.getValue().add(containerId);
        assignmentQueue.add(leastLoadedServer);
    }

    // 8. rebalance the containers if needed
    int diffAllowed;
    if (assignmentQueue.size() > clusterMetadata.getNumStorageContainers()) {
        diffAllowed = 1;
    } else {
        diffAllowed = clusterMetadata.getNumStorageContainers() % assignmentQueue.size() == 0 ? 0 : 1;
    }

    Pair<BookieSocketAddress, LinkedList<Long>> leastLoaded = assignmentQueue.first();
    Pair<BookieSocketAddress, LinkedList<Long>> mostLoaded = assignmentQueue.last();
    while (mostLoaded.getValue().size() - leastLoaded.getValue().size() > diffAllowed) {
        leastLoaded = assignmentQueue.pollFirst();
        mostLoaded = assignmentQueue.pollLast();

        // move container from mostLoaded to leastLoaded
        Long containerId = mostLoaded.getValue().removeFirst();
        // add the container to the end to avoid balancing this container again.
        leastLoaded.getValue().addLast(containerId);

        assignmentQueue.add(leastLoaded);
        assignmentQueue.add(mostLoaded);

        leastLoaded = assignmentQueue.first();
        mostLoaded = assignmentQueue.last();
    }

    // 9. the new ideal state is computed, finalize it
    Map<String, ServerAssignmentData> newAssignmentMap = Maps.newHashMap();
    assignmentQueue.forEach(assignment -> newAssignmentMap.put(assignment.getKey().toString(),
            ServerAssignmentData.newBuilder().addAllContainers(assignment.getValue()).build()));
    return ClusterAssignmentData.newBuilder().putAllServers(newAssignmentMap).build();
}