简体   繁体   English

使用fork-join的Java多路树搜索

[英]Java multi-way tree searching using fork-join

I have multi-way tree structure, which i have to traverse to determine status. 我具有多向树结构,必须遍历以确定其状态。 I am looking into 'Post-Order' type traversal where leaf nodes are processed first. 我正在研究“后订单”类型遍历,其中先处理叶节点。 And search end condition depends on any of child node having status inactive. 搜索结束条件取决于状态为非活动的子节点中的任何一个。 Also, from performance perspective, i would to use JDK7's fork-join mechanism. 另外,从性能角度来看,我将使用JDK7的fork-join机制。

在此处输入图片说明

Here is a (very) rough sketch of how you could do it. 这是一个(非常)大概的草图。

final class TreeNode {
    private final Iterable<TreeNode> children;

    TreeNode(Iterable<TreeNode> aChildren) {
        children = aChildren;
    }

    Iterable<TreeNode> getChildren() {
        return children;
    }

    void postorder(TreeNodeIterator iterator) {
        postorderTraverse(this, iterator);
    }

    private void postorderTraverse(TreeNode node, TreeNodeIterator iterator) {
        for (TreeNode child : children) {
            postorderTraverse(child, iterator);
        }
        iterator.visit(node);
    }

    void postorderParallel(TreeNodeIterator iterator) {
        new ForkJoinPool().invoke(new VisitNodeAction(iterator, this));
    }

    interface TreeNodeIterator {
        void visit(TreeNode child);
    }

    private class VisitNodeAction extends RecursiveAction {
        private final TreeNodeIterator iterator;
        private final TreeNode node;

        private VisitNodeAction(TreeNodeIterator iterator, TreeNode node) {
            this.iterator = iterator;
            this.node = node;
        }

        @Override
        protected void compute() {
            List<RecursiveAction> tasks = new LinkedList<RecursiveAction>();
            for (TreeNode child : children) {
                tasks.add(new VisitNodeAction(iterator, child));
            }
            invokeAll(tasks);
            iterator.visit(node);
        }
    }
}

Some things that would need to be modified: 有些事情需要修改:

  • Adding your check for the status being inactive. 添加检查状态是否为非活动状态。 Easiest way would be to keep a atomic boolean in each RecursiveAction that is checked before processing the node and updated when a node is inactive, although this is not a very clean or functional route. 最简单的方法是在每个RecursiveAction中保留一个原子布尔值,该布尔值在处理节点之前进行检查,并在节点处于非活动状态时进行更新,尽管这不是很干净或实用的路由。
  • Adding a way to decide when new threads should be used, the above uses a thread for every node. 添加了一种决定何时应使用新线程的方法,以上方法为每个节点使用了一个线程。 Also, you could possibly optimize it a bit by not creating a ForkJoinPool on every invocation of postorderParallel . 此外,您可能会因不能创建一个优化有点ForkJoinPool上的每次调用postorderParallel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM