这个字数螺栓螺纹如何安全? [英] How is this word count bolt thread safe?

查看:84
本文介绍了这个字数螺栓螺纹如何安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是暴风雨的新手,我正在经历暴风雨的字数示例.这是跟踪计数的螺栓

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"));
    }
  }

据我了解,storm为螺栓并行启动了多个线程,那么如何在这里使用HashMap保证线程安全?

From my understand, storm launches multiple threads for bolt which run in parallel, so how is using HashMap here thread-safe?

推荐答案

[螺栓和喷嘴]不需要是线程安全的.每个任务都有自己的 他们正在执行的螺栓或喷口对象的实例,以及任何对象 给定任务Storm会在单个线程上调用所有spout/bolt方法.

[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.

这篇关于这个字数螺栓螺纹如何安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆