多线程map

本文介绍了如何使用多线程技术优化MapReduce中的Map阶段,通过自定义的MultithreadedMapper类,将原本耗时的CPU密集型作业从55小时缩短到7小时。文中提供了一个多线程Map的示例代码,并详细解释了类的内部工作原理,包括线程池的配置、子任务的执行以及数据同步等关键部分。
摘要由CSDN通过智能技术生成

概述

  • 作用
  • 应用场景
  • 效果
  • 代码示例
作用
  • 想在 map 或 reduce 里启动多线程
应用场景
  • map reduce 端 cpu 型作业
效果
  • 公司原来一个 cpu 型算法作业,20 台服务器 以前运行需 55 个小时左右,改用我自己改进的多线程后,同样的前提条件,只须运行 7 小时
代码示例
  • 多线程map 示例代码
  • 自带的 多线程map 源代码
  • public class MultithreadedMapper<K1, V1, K2, V2> 
      extends Mapper<K1, V1, K2, V2> {
    
      private static final Log LOG = LogFactory.getLog(MultithreadedMapper.class);
      private Class<? extends Mapper<K1,V1,K2,V2>> mapClass;
      private Context outer;
      private List<MapRunner> runners;
    
      /**
       * The number of threads in the thread pool that will run the map function.
       * @param job the job
       * @return the number of threads
       */
      public static int getNumberOfThreads(JobContext job) {
        return job.getConfiguration().
                getInt("mapred.map.multithreadedrunner.threads", 10);
      }
    
      /**
       * Set the number of threads in the pool for running maps.
       * @param job the job to modify
       * @param threads the new number of threads
       */
      public static void setNumberOfThreads(Job job, int threads) {
        job.getConfiguration().setInt("mapred.map.multithreadedrunner.threads", 
                                      threads);
      }
    
      /**
       * Get the application's mapper class.
       * @param <K1> the map's input key type
       * @param <V1> the map's input value type
       * @param <K2> the map's output key type
       * @param <V2> the map's output value type
       * @param job the job
       * @return the mapper class to run
       */
      @SuppressWarnings("unchecked")
      public static <K1,V1,K2,V2>
      Class<Mapper<K1,V1,K2,V2>> getMapperClass(JobContext job) {
        return (Class<Mapper<K1,V1,K2,V2>>) 
             job.getConfiguration().getClass("mapred.map.multithreadedrunner.class",
                                             Mapper.class);
      }
      
      /**
       * Set the application's mapper class.
       * @param <K1> the map input key type
       * @param <V1> the map input value type
       * @param <K2> the map output key type
       * @param <V2> the map output value type
       * @param job the job to modify
       * @param cls the class to use as the mapper
       */
     
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值