加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java是否自动并行化递归函数?

发布时间:2020-12-15 08:27:57 所属栏目:Java 来源:网络整理
导读:我正在并行递归函数,我测得加速不佳.在调试代码时,我注意到在顺序版本中所有内核都在工作. 我在一个最小的例子中重现了这种行为,而且我的所有内核的工作负载都是大约90%.我正在使用Java 8(OpenJDK). Java是否在我不知情的情况下自动进行并行化? Java如何做
我正在并行递归函数,我测得加速不佳.在调试代码时,我注意到在顺序版本中所有内核都在工作.

我在一个最小的例子中重现了这种行为,而且我的所有内核的工作负载都是大约90%.我正在使用Java 8(OpenJDK).

Java是否在我不知情的情况下自动进行并行化? Java如何做到这一点?

import java.util.Random;
import java.util.ArrayList;

class Node
{
    float value;
    ArrayList<Node> children;

    public Node()
    {
        children = new ArrayList<Node>();
    }

    public Node(float value)
    {
        this.value = value;
    }

    public int count()
    {
        int count = 1;

        if (children != null)
            for (Node c : children)
                count += c.count();

        return count;
    }
}

public class ProofOfConcept {
    final static int N_NODES = 10000000;
    final static int MAX_CHILDREN = 6;

    final static Random RAND = new Random();

    static Node generateTree(int nNodes)
    {
        if (nNodes > 1)
        {
            Node result = new Node();
            int nChildren = 1 + RAND.nextInt(Math.min(MAX_CHILDREN,nNodes) - 1);
            int nNodesPerChild = (nNodes - 1) / nChildren;

            for (int i = 0; i < nChildren; ++i)
            {
                Node t = generateTree(nNodesPerChild);
                result.children.add(t);
            }

            return result;
        }
        else
            return new Node(RAND.nextFloat());
    }

    public static void main(String[] args)
    {
        Node t = generateTree(N_NODES);
        System.out.println(t.count());
    }
}

编辑:这对我来说也很奇怪.我附上了htop的截图;正如您所看到的,我们有主进程和八个线程(每个逻辑核心一个).

htop

编辑2:似乎GC正在并行工作.对于那些不明白为什么GC被触发的人,如果显然没有被释放的对象,你应该阅读following reference:

When a garbage collection is triggered by an allocation failure,but the garbage collection does not free enough space,the Garbage Collector expands the storage heap. During heap expansion,the Garbage Collector takes storage from the maximum amount of storage reserved for the heap (the amount specified by the -Xmx option),and adds it to the active part of the heap (which began as the size specified by the -Xms option). Heap expansion does not increase the amount of storage required for the JVM,because the maximum amount of storage specified by the -Xmx option has already been allocated to the JVM at startup. If the value of the -Xms option provides sufficient storage in the active part of the heap for your applications,the Garbage Collector does not have to carry out heap expansion at all.

解决方法

不,Java并没有神奇地使你的代码并行.

如果您在所有核心上看到90%的利用率,则可以是操作系统,其他进程或JVM进行后台工作.它可能是JVM使用并行GC利用所有核心来收集垃圾.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读