Skip to content

Commit

Permalink
* Don't try to remove already removed element during removeFirstIndep…
Browse files Browse the repository at this point in the history
…endent

* Presize the LinkedHashMap correctly

Signed-off-by: Lukas Krejci <lkrejci@redhat.com>
  • Loading branch information
metlos committed Feb 25, 2019
1 parent 53787f0 commit 9a8a4f8
Showing 1 changed file with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*/
package org.eclipse.che.commons.lang;

import static com.google.common.collect.Maps.newLinkedHashMapWithExpectedSize;
import static java.util.Collections.emptyList;

import java.util.ArrayList;
Expand Down Expand Up @@ -84,7 +85,7 @@ public TopologicalSort(
public List<N> sort(Collection<N> nodes) {
// the linked hashmap is important to retain the original order of elements unless required
// by the dependencies between nodes
LinkedHashMap<ID, NodeInfo<ID, N>> nodeInfos = new LinkedHashMap<>(nodes.size());
LinkedHashMap<ID, NodeInfo<ID, N>> nodeInfos = newLinkedHashMapWithExpectedSize(nodes.size());
List<NodeInfo<ID, N>> results = new ArrayList<>(nodes.size());

int pos = 0;
Expand All @@ -93,7 +94,7 @@ public List<N> sort(Collection<N> nodes) {
ID nodeID = identityExtractor.apply(node);
// we need the set to be modifiable, so let's make our own
Set<ID> preds = new HashSet<>(directPredecessorsExtractor.apply(node));
needsSorting |= !preds.isEmpty();
needsSorting = needsSorting || !preds.isEmpty();

NodeInfo<ID, N> nodeInfo = nodeInfos.computeIfAbsent(nodeID, __ -> new NodeInfo<>());
nodeInfo.id = nodeID;
Expand Down Expand Up @@ -174,6 +175,11 @@ private void sort(LinkedHashMap<ID, NodeInfo<ID, N>> nodes, List<NodeInfo<ID, N>
}

private void removePredecessorMapping(Map<ID, NodeInfo<ID, N>> nodes, NodeInfo<ID, N> node) {
forgetNodeInSuccessors(node, nodes);
nodes.remove(node.id);
}

private void forgetNodeInSuccessors(NodeInfo<ID, N> node, Map<ID, NodeInfo<ID, N>> nodes) {
if (node.successors != null) {
for (ID succ : node.successors) {
NodeInfo<ID, N> succNode = nodes.get(succ);
Expand All @@ -182,7 +188,6 @@ private void removePredecessorMapping(Map<ID, NodeInfo<ID, N>> nodes, NodeInfo<I
}
}
}
nodes.remove(node.id);
}

private List<NodeInfo<ID, N>> findCycle(NodeInfo<ID, N> node, Map<ID, NodeInfo<ID, N>> nodes) {
Expand Down Expand Up @@ -229,7 +234,7 @@ private NodeInfo<ID, N> removeFirstIndependent(Map<ID, NodeInfo<ID, N>> nodes) {
if (e.getValue().predecessors.isEmpty()) {
it.remove();
NodeInfo<ID, N> ret = e.getValue();
removePredecessorMapping(nodes, ret);
forgetNodeInSuccessors(ret, nodes);
return ret;
}
}
Expand Down

0 comments on commit 9a8a4f8

Please sign in to comment.