Java 使用ForkJoin和Streams构建自适应网格细化
我想在3D中建立一个自适应的网格细化 基本原则如下: 我有一组具有唯一单元格ID的单元格。 我测试每个单元格,看它是否需要改进Java 使用ForkJoin和Streams构建自适应网格细化,java,concurrency,java-stream,fork-join,Java,Concurrency,Java Stream,Fork Join,我想在3D中建立一个自适应的网格细化 基本原则如下: 我有一组具有唯一单元格ID的单元格。 我测试每个单元格,看它是否需要改进 如果需要优化,a将创建8个新的子单元格,并将它们添加到单元格列表中以检查优化 否则,这是一个叶节点,我将其添加到叶节点列表中 我想使用ForkJoin框架和Java8流实现它。我读过,但我不知道如何把它应用到我的案例中 现在,我想到的是: public class ForkJoinAttempt { private final double[] cellId
- 如果需要优化,a将创建8个新的子单元格,并将它们添加到单元格列表中以检查优化
- 否则,这是一个叶节点,我将其添加到叶节点列表中
public class ForkJoinAttempt {
private final double[] cellIds;
public ForkJoinAttempt(double[] cellIds) {
this.cellIds = cellIds;
}
public void refineGrid() {
ForkJoinPool pool = ForkJoinPool.commonPool();
double[] result = pool.invoke(new RefineTask(100));
}
private class RefineTask extends RecursiveTask<double[]> {
final double cellId;
private RefineTask(double cellId) {
this.cellId = cellId;
}
@Override
protected double[] compute() {
return ForkJoinTask.invokeAll(createSubtasks())
.stream()
.map(ForkJoinTask::join)
.reduce(new double[0], new Concat());
}
}
private double[] refineCell(double cellId) {
double[] result;
if (checkCell()) {
result = new double[8];
for (int i = 0; i < 8; i++) {
result[i] = Math.random();
}
} else {
result = new double[1];
result[0] = cellId;
}
return result;
}
private Collection<RefineTask> createSubtasks() {
List<RefineTask> dividedTasks = new ArrayList<>();
for (int i = 0; i < cellIds.length; i++) {
dividedTasks.add(new RefineTask(cellIds[i]));
}
return dividedTasks;
}
private class Concat implements BinaryOperator<double[]> {
@Override
public double[] apply(double[] a, double[] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
double[] c = (double[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
}
public boolean checkCell() {
return Math.random() < 0.5;
}
}
以及测试它的方法:
int initialSize = 4;
List<Long> cellIds = new ArrayList<>(initialSize);
for (int i = 0; i < initialSize; i++) {
cellIds.add(Long.valueOf(i + 1));
}
ForkJoinAttempt test = new ForkJoinAttempt();
test.refineGrid(cellIds);
List<Long> leafCellIds = test.getLeafCellIds();
System.out.println("Leaf nodes: " + leafCellIds.size());
for (Long node : leafCellIds) {
System.out.println(node);
}
int initialSize=4;
List cellIds=newarraylist(initialSize);
对于(int i=0;i
输出确认向每个根单元格添加8个子项。但它并没有走得更远
我知道原因,但我不知道如何解决它:这是因为即使使用refineCell方法将新单元格添加到要处理的单元格列表中。createSubTask方法不会再次调用,因此它无法知道我已添加了新单元格
编辑2:
为了说明不同的问题,我要寻找的是一种机制,其中一个单元格ID的
队列
由一些递归任务
处理,而另一些则并行添加到队列
。首先,让我们从基于流的解决方案开始
public class Mesh {
public static long[] refineGrid(long[] cellsToProcess) {
return Arrays.stream(cellsToProcess).parallel().flatMap(Mesh::expand).toArray();
}
static LongStream expand(long d) {
return checkCell(d)? LongStream.of(d): generate(d).flatMap(Mesh::expand);
}
private static boolean checkCell(long cellId) {
return cellId > 100;
}
private static LongStream generate(long cellId) {
return LongStream.range(0, 8).map(j -> cellId * 10 + j);
}
}
虽然当前的flatMap
实现具有并行处理功能,可能在网格过于不平衡时应用,但实际任务的性能可能是合理的,因此在开始实现更复杂的功能之前,此简单解决方案始终值得一试
如果您确实需要自定义实现,例如,如果工作负载不平衡,流实现无法很好地适应,您可以这样做:
public class MeshTask extends RecursiveTask<long[]> {
public static long[] refineGrid(long[] cellsToProcess) {
return new MeshTask(cellsToProcess, 0, cellsToProcess.length).compute();
}
private final long[] source;
private final int from, to;
private MeshTask(long[] src, int from, int to) {
source = src;
this.from = from;
this.to = to;
}
@Override
protected long[] compute() {
return compute(source, from, to);
}
private static long[] compute(long[] source, int from, int to) {
long[] result = new long[to - from];
ArrayDeque<MeshTask> next = new ArrayDeque<>();
while(getSurplusQueuedTaskCount()<3) {
int mid = (from+to)>>>1;
if(mid == from) break;
MeshTask task = new MeshTask(source, mid, to);
next.push(task);
task.fork();
to = mid;
}
int pos = 0;
for(; from < to; ) {
long value = source[from++];
if(checkCell(value)) result[pos++]=value;
else {
long[] array = generate(value);
array = compute(array, 0, array.length);
result = Arrays.copyOf(result, result.length+array.length-1);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
while(from == to && !next.isEmpty()) {
MeshTask task = next.pop();
if(task.tryUnfork()) {
to = task.to;
}
else {
long[] array = task.join();
int newLen = pos+to-from+array.length;
if(newLen != result.length)
result = Arrays.copyOf(result, newLen);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
}
}
return result;
}
static boolean checkCell(long cellId) {
return cellId > 1000;
}
static long[] generate(long cellId) {
long[] sub = new long[8];
for(int i = 0; i < sub.length; i++) sub[i] = cellId*10+i;
return sub;
}
}
公共类MeshTask扩展了RecursiveTask{
公共静态长[]网格(长[]cellsToProcess){
返回新的MeshTask(cellsToProcess,0,cellsToProcess.length).compute();
}
私人最终长[]来源;
私人最终整数从,到;
私有MeshTask(long[]src,int-from,int-to){
来源=src;
this.from=from;
这个;
}
@凌驾
受保护的长[]计算(){
返回计算(源、从、到);
}
专用静态long[]计算(long[]源,int-from,int-to){
long[]结果=新的long[to-from];
ArrayDeque next=新的ArrayDeque();
而(get盈余queuedtaskcount()>>1;
如果(中间==起始)中断;
MeshTask任务=新的MeshTask(源、中、到);
下一步。推(任务);
task.fork();
to=中期;
}
int pos=0;
对于(;从<到;){
长值=源[from++];
如果(检查单元(值))结果[pos++]=值;
否则{
long[]数组=生成(值);
array=compute(array,0,array.length);
结果=Arrays.copyOf(结果,结果.长度+数组.长度-1);
数组复制(数组,0,结果,位置,数组长度);
pos+=数组长度;
}
while(from==to&&!next.isEmpty()){
MeshTask task=next.pop();
if(task.tryUnfork()){
to=task.to;
}
否则{
long[]数组=task.join();
int newLen=pos+到from+array.length;
if(newLen!=结果长度)
结果=Arrays.copyOf(结果,newLen);
数组复制(数组,0,结果,位置,数组长度);
pos+=数组长度;
}
}
}
返回结果;
}
静态布尔校验单元(长单元ID){
返回细胞数>1000;
}
静态长[]生成(长单元ID){
long[]sub=新long[8];
对于(inti=0;i
此实现直接调用根任务的compute
方法,以将调用线程合并到计算中。compute
方法用于决定是否拆分。正如其文档所述,其思想是始终有少量剩余,例如3
。这确保评估可以适应unb平衡工作负载,因为空闲线程可以从其他任务窃取工作
拆分不是通过创建两个子任务并等待两个子任务来完成的。相反,只拆分一个任务,表示挂起工作的后半部分,并且调整当前任务的工作负载以反映前半部分
然后,本地处理剩余的工作负载。之后,弹出最后一个推送的子任务并尝试执行。如果取消格式化成功,则调整当前工作负载的范围以覆盖后续任务的范围,并继续本地迭代
这样,任何未被另一个线程窃取的剩余任务都将以最简单、最轻量级的方式进行处理,就好像它从未被分叉一样
如果任务已被另一个线程拾取,我们现在必须等待其完成并合并结果数组
请注意,当通过join()
等待子任务时,底层实现还将检查是否可以进行取消格式化和局部求值,以使所有工作线程保持忙碌。但是,调整循环变量并直接在目标数组中累积结果仍然比嵌套的计算调用要好
public class MeshTask extends RecursiveTask<long[]> {
public static long[] refineGrid(long[] cellsToProcess) {
return new MeshTask(cellsToProcess, 0, cellsToProcess.length).compute();
}
private final long[] source;
private final int from, to;
private MeshTask(long[] src, int from, int to) {
source = src;
this.from = from;
this.to = to;
}
@Override
protected long[] compute() {
return compute(source, from, to);
}
private static long[] compute(long[] source, int from, int to) {
long[] result = new long[to - from];
ArrayDeque<MeshTask> next = new ArrayDeque<>();
while(getSurplusQueuedTaskCount()<3) {
int mid = (from+to)>>>1;
if(mid == from) break;
MeshTask task = new MeshTask(source, mid, to);
next.push(task);
task.fork();
to = mid;
}
int pos = 0;
for(; from < to; ) {
long value = source[from++];
if(checkCell(value)) result[pos++]=value;
else {
long[] array = generate(value);
array = compute(array, 0, array.length);
result = Arrays.copyOf(result, result.length+array.length-1);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
while(from == to && !next.isEmpty()) {
MeshTask task = next.pop();
if(task.tryUnfork()) {
to = task.to;
}
else {
long[] array = task.join();
int newLen = pos+to-from+array.length;
if(newLen != result.length)
result = Arrays.copyOf(result, newLen);
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
}
}
return result;
}
static boolean checkCell(long cellId) {
return cellId > 1000;
}
static long[] generate(long cellId) {
long[] sub = new long[8];
for(int i = 0; i < sub.length; i++) sub[i] = cellId*10+i;
return sub;
}
}