How is this word count bolt thread safe?

我怕爱的太早我们不能终老 提交于 2020-01-14 03:13:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!