问题
I am new with storm, I was going through the word count example of storm. Here is the bolt which keeps track of the counts
public static class WordCount extends BaseBasicBolt {
Map<String, Integer> counts = new HashMap<String, Integer>();
@Override
public void execute(Tuple tuple, BasicOutputCollector collector) {
String word = tuple.getString(0);
Integer count = counts.get(word);
if (count == null)
count = 0;
count++;
counts.put(word, count);
collector.emit(new Values(word, count));
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word", "count"));
}
}
From my understand, storm launches multiple threads for bolt which run in parallel, so how is using HashMap here thread-safe?
回答1:
[Bolts and spouts] do not need to be thread-safe. Each task has their own instance of the bolt or spout object they're executing, and for any given task Storm calls all spout/bolt methods on a single thread.
来源:https://stackoverflow.com/questions/36349152/how-is-this-word-count-bolt-thread-safe