我正在查看没有意义的 hadoop 框架中的生产代码。为什么我们要使用 transient 以及为什么我不能将实用程序方法设为静态方法(领导告诉我们不要将 isThinger 设为静态方法)?查了一下transient关键字,跟序列化有关。这里真的用到连载了吗?
//extending from MapReduceBase is a requirement of hadoop
public static class MyMapper extends MapReduceBase {
// why the use of transient keyword here?
transient Utility utility;
public void configure(JobConf job) {
String test = job.get("key");
// seems silly that we have to create Utility instance.
// can't we use a static method instead?
utility = new Utility();
boolean res = utility.isThinger(test);
foo (res);
}
void foo (boolean a) { }
}
public class Utility {
final String stringToSearchFor = "ineverchange";
// it seems we could make this static. Why can't we?
public boolean isThinger(String word) {
boolean val = false;
if (word.indexOf(stringToSearchFor) > 0) {
val = true;
}
return val;
}
}
最佳答案
您的代码中的问题是本地模式(开发和测试用例通常使用它)和分布式模式之间的区别。
在本地模式下,所有内容都将在单个 JVM 中,因此您可以安全地假设如果您更改静态变量(或共享某些状态的静态方法,在您的情况下为 stringToSearchFor
)对于每个输入 block 的计算,更改都是可见的。
在分布式模式下,每个 block 都在其自己的 JVM 中处理。因此,如果您更改状态(例如在 stringToSearchFor
中),这对于在其他主机/jvms/任务上运行的所有其他进程都是不可见的。
这种不一致导致在编写 map/reduce 函数时遵循以下设计原则:
- 尽可能无状态。
- 如果您需要状态(例如可变类),永远不要在 map/reduce 类
static
中声明引用(否则它在测试/开发时的行为与在制作) - 不可变常量(例如作为
String
的配置键)应定义为static
和final
。
transient
在 Hadoop 中几乎没有用,Hadoop 没有序列化用户代码(Mapper/Reducer)类/对象中的任何内容。仅当您对我们不知道的 Java 序列化执行某些操作时,这才会成为问题。
对于您的情况,如果 Utility
确实是一个实用程序并且 stringToSearchFor
是一个不可变常量(因此永远不会更改),您可以安全地将 isThinger
声明为 static
。如果您不使用 MapReduceBase
进行任何 Java 序列化,请删除 transient
。
关于java - hadoop中的 transient 变量和静态方法,dev求教,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14743530/