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

我正在并行递归函数,我测得加速不佳.在调试代码时,我注意到在顺序版本中所有内核都在工作.

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

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

import java.util.Random;

import java.util.ArrayList;

class Node

{

float value;

ArrayList children;

public Node()

{

children = new ArrayList();

}

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的截图;正如您所看到的,我们有主进程和八个线程(每个逻辑核心一个).

JdJ8T.png

编辑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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值