我正在并行递归函数,我测得加速不佳.在调试代码时,我注意到在顺序版本中所有内核都在工作.
我在一个最小的例子中重现了这种行为,而且我的所有内核的工作负载都是大约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的截图;正如您所看到的,我们有主进程和八个线程(每个逻辑核心一个).
编辑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.