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

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

问题描述

我是 Storm 的新手,我正在浏览 Storm 的字数统计示例.这是跟踪计数的螺栓

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 为 bolt 启动了多个并行运行的线程,那么这里如何使用 HashMap 线程安全?

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

推荐答案

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

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

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