任务未读取 Spark 累加器值

Spark Accumulator value not read by task

我正在初始化一个累加器

final Accumulator<Integer> accum = sc.accumulator(0);

然后在 map 函数中,我尝试递增累加器,然后在设置变量时使用累加器值。

JavaRDD<UserSetGet> UserProfileRDD1 = temp.map(new Function<String, UserSetGet>() {

            @Override
            public UserSetGet call(String arg0) throws Exception {

                    UserSetGet usg = new UserSetGet();

                    accum.add(1);
                    usg.setPid(accum.value().toString();


            }
  });

但是我收到以下错误。

16/03/14 09:12:58 ERROR executor.Executor: Exception in task 0.0 in stage 2.0 (TID 2) java.lang.UnsupportedOperationException: Can't read accumulator value in task

已编辑 - 根据 Avihoo Mamka 的回答,在任务中获取累加器值是不可能的。

所以无论如何我可以并行实现相同的目标。这样每次在我的映射函数中递增变量(例如静态变量)时都会设置 Pid 值。

来自Spark docs

Accumulators are variables that are only “added” to through an associative operation and can therefore be efficiently supported in parallel. They can be used to implement counters (as in MapReduce) or sums

...

Only the driver program can read the accumulator’s value, using its value method.

因此,当尝试从 Spark 中的任务中读取累加器的值时,意味着您尝试从工作人员中读取其值,这与仅从驱动程序中读取累加器值的概念背道而驰。