我正在尝试为BFS图算法编写迭代mapreduce
为了指定何时停止迭代,我尝试使用计数器
该代码是
public class GraphSearch extends Configured implements Tool {
static int counter=0;
public static class MapClass extends MapReduceBase implements
Mapper<LongWritable, Text, IntWritable, Text> {
public void map(LongWritable key, Text value, OutputCollector<IntWritable, Text> output,
Reporter reporter) throws IOException {
Node node = new Node(value.toString()) ;
if (node.getColor() == Node.Color.GRAY) {
if(node.getDistance()==Integer.MAX_VALUE)
node.setDistance(0);
for (int v : node.getEdges()) {
Node vnode = new Node(v);
vnode.setDistance(node.getDistance() + 1);
vnode.setColor(Node.Color.GRAY);
output.collect(new IntWritable(vnode.getId()), vnode.getLine());
}
node.setColor(Node.Color.BLACK);
setCounter(1);
}
output.collect(new IntWritable(node.getId()), node.getLine());
}
static void setCounter(int i) {
if(i==1)
counter=counter+1;
else
counter=0;
}
这个想法是当计数器保持为0时,这意味着遍历所有节点(所有节点都变成黑色)并且BFS完成
private boolean checkForConvergence(int iteration_number){
if(counter!=0&&iteration_number!=0){
return true;
}
return false
}
但是setCounter没有显示计数器值的任何变化。
该怎么办?
还有其他方法可以在Java中拥有全局变量(就像在c++中一样,这非常简单-只需在所有内容外部声明它)?
最佳答案
目前尚不清楚您在做什么,但是无论如何:您需要在Hadoop作业类static
类中声明GraphSearch
计数器变量。 Hadoop作业在其自己的JVM中的hadoop节点上运行。 hadoop中的映射器在单独的JVM中运行,并具有自己的此变量实例。这就是您的代码无法正常工作的原因。
我不知道您的算法应该如何工作,所以我不建议任何更改。从Hadoop tutorials开始,了解映射约简算法的思想。
关于java - 映射器函数中的静态变量值未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41280397/