Netty核心组件EventLoop详解

Netty 4.1.49.Final 入门实战:3步构建Echo服务器与客户端(附完整代码) 本文详细介绍了如何使用Netty 4.1.49.Final快速构建高性能Echo服务器与客户端,包含完整代码示例和核心组件解析。通过io.netty框架,开发者可以轻松实现网络通信功能,并了解Netty的线程模型、ChannelHandler等关键概念,为构建更复杂的网络应用打下基础。 阅读详情

Netty 核心组件 EventLoop 详解

一、什么是 EventLoop?

EventLoop 可以理解为 Netty 中的"工人",它的核心职责是:

  1. 处理 I/O 事件:读取数据、写入数据、连接建立等
  2. 执行普通任务:用户提交的自定义任务
  3. 执行定时任务:周期性执行的任务

本质

EventLoop = 单线程执行器 + Selector(选择器)

  • 每个 EventLoop 内部有一个线程
  • 每个 EventLoop 维护一个 Selector,用于监听多个 Channel 的 I/O 事件
  • EventLoop 通过 run() 方法不断循环处理事件

继承关系

EventLoop
    ├── 继承 ScheduledExecutorService(Java 线程池)
    │   └── 拥有线程池的所有方法(execute、submit、schedule 等)
    │
    └── 继承 OrderedEventExecutor(Netty 自定义)
        ├── inEventLoop(Thread thread):判断线程是否属于此 EventLoop
        └── parent():查看属于哪个 EventLoopGroup

二、什么是 EventLoopGroup?

EventLoopGroup 是一组 EventLoop 的集合,可以理解为"工人组"。

核心特性

  1. Channel 绑定:每个 Channel 会绑定到 EventLoopGroup 中的某一个 EventLoop
  2. 线程安全:同一个 Channel 的所有 I/O 事件都由同一个 EventLoop 处理,保证线程安全
  3. 负载均衡:多个 Channel 会轮流分配给不同的 EventLoop

继承关系

EventLoopGroup
    ├── 继承 EventExecutorGroup
    │   ├── 实现 Iterable 接口(可以遍历 EventLoop)
    │   └── next() 方法:获取下一个 EventLoop

三、EventLoopGroup 基本使用

示例 1:创建 EventLoopGroup

// 创建包含 2 个 EventLoop 的组
DefaultEventLoopGroup group = new DefaultEventLoopGroup(2);

// 获取 EventLoop(轮流获取)
System.out.println(group.next()); // EventLoop-1
System.out.println(group.next()); // EventLoop-2
System.out.println(group.next()); // EventLoop-1(循环)

输出:

io.netty.channel.DefaultEventLoop@60f82f98
io.netty.channel.DefaultEventLoop@35f983a6
io.netty.channel.DefaultEventLoop@60f82f98

示例 2:遍历 EventLoopGroup

DefaultEventLoopGroup group = new DefaultEventLoopGroup(2);
for (EventExecutor eventLoop : group) {
    System.out.println(eventLoop);
}

输出:

io.netty.channel.DefaultEventLoop@60f82f98
io.netty.channel.DefaultEventLoop@35f983a6

四、优雅关闭

shutdownGracefully() 方法

group.shutdownGracefully();

执行流程:

  1. 切换 EventLoopGroup 到关闭状态,拒绝新任务
  2. 等待任务队列中的任务执行完成
  3. 停止所有线程

作用: 确保应用在正常有序的状态下退出,避免任务丢失。


五、EventLoop 处理 I/O 事件

场景:服务端使用 2 个 Worker 线程

服务端代码:

new ServerBootstrap()
    .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
    //     ↑ Boss Group (1个线程)    ↑ Worker Group (2个线程)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ByteBuf byteBuf = (ByteBuf) msg;
                    byte[] buf = new byte[byteBuf.readableBytes()];
                    byteBuf.readBytes(buf);
                    log.debug(new String(buf));
                }
            });
        }
    }).bind(8080).sync();

客户端代码(启动 3 次,分别发送 “zhangsan”、“lisi”、“wangwu”):

Channel channel = new Bootstrap()
    .group(new NioEventLoopGroup(1))
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) {
            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        }
    })
    .connect("localhost", 8080)
    .sync()
    .channel();

channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("zhangsan".getBytes()));
Thread.sleep(2000);
channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("zhangsan".getBytes()));

输出结果:

22:03:34 [DEBUG] [nioEventLoopGroup-3-1] - zhangsan       
22:03:36 [DEBUG] [nioEventLoopGroup-3-1] - zhangsan       
22:05:36 [DEBUG] [nioEventLoopGroup-3-2] - lisi           
22:05:38 [DEBUG] [nioEventLoopGroup-3-2] - lisi           
22:06:09 [DEBUG] [nioEventLoopGroup-3-1] - wangwu        
22:06:11 [DEBUG] [nioEventLoopGroup-3-1] - wangwu         

分析

  • Worker Group 有 2 个线程:nioEventLoopGroup-3-1 和 nioEventLoopGroup-3-2
  • Channel 与 EventLoop 绑定:
    • 第 1 个客户端 → 绑定到 EventLoop-1
    • 第 2 个客户端 → 绑定到 EventLoop-2
    • 第 3 个客户端 → 绑定到 EventLoop-1(轮流分配)
  • 同一个 Channel 的所有事件都由同一个 EventLoop 处理

图示:

客户端1 (zhangsan) ──→ EventLoop-1 (线程1)
客户端2 (lisi)     ──→ EventLoop-2 (线程2)
客户端3 (wangwu)   ──→ EventLoop-1 (线程1)

六、分工:NIO EventLoop + 普通 EventLoop

场景:将耗时任务交给普通 EventLoop 处理

为什么需要分工?

  • NIO EventLoop 负责处理 I/O 事件(读写数据)
  • 如果业务逻辑耗时较长(如数据库查询),会阻塞 I/O 处理
  • 解决方案:将耗时任务交给普通 EventLoop 处理

服务端代码:

// 创建 2 个普通工人(非 NIO)
DefaultEventLoopGroup normalWorkers = new DefaultEventLoopGroup(2);

new ServerBootstrap()
    .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) {
            // 第 1 个 handler:由 NIO EventLoop 处理
            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
            
            // 第 2 个 handler:由普通 EventLoop 处理
            ch.pipeline().addLast(normalWorkers, "myhandler",
                new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                        ByteBuf byteBuf = (ByteBuf) msg;
                        byte[] buf = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(buf);
                        log.debug(new String(buf));
                    }
                });
        }
    }).bind(8080).sync();

输出结果:

22:19:48 [DEBUG] [nioEventLoopGroup-4-1] LoggingHandler - READ: 8B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 7a 68 61 6e 67 73 61 6e                         |zhangsan        |
+--------+-------------------------------------------------+----------------+
22:19:48 [DEBUG] [defaultEventLoopGroup-2-1] - zhangsan        

22:20:24 [DEBUG] [nioEventLoopGroup-4-2] LoggingHandler - READ: 4B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 6c 69 73 69                                     |lisi            |
+--------+-------------------------------------------------+----------------+
22:20:25 [DEBUG] [defaultEventLoopGroup-2-2] - lisi            

22:20:38 [DEBUG] [nioEventLoopGroup-4-1] LoggingHandler - READ: 6B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 77 61 6e 67 77 75                               |wangwu          |
+--------+-------------------------------------------------+----------------+
22:20:38 [DEBUG] [defaultEventLoopGroup-2-1] - wangwu          

分析

  • LoggingHandler 由 NIO EventLoop 执行(nioEventLoopGroup-4-1)
  • 自定义 Handler 由普通 EventLoop 执行(defaultEventLoopGroup-2-1)
  • 实现了分工:I/O 操作和业务逻辑分离

图示:

客户端数据到达
    ↓
NIO EventLoop (线程1) 
    ↓ 执行 LoggingHandler(记录日志)
    ↓
普通 EventLoop (线程3)
    ↓ 执行自定义 Handler(业务逻辑)

七、Handler 执行中如何换人?

核心代码:invokeChannelRead()

static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
    EventExecutor executor = next.executor();
    
    // 判断下一个 handler 的线程是否与当前线程相同
    if (executor.inEventLoop()) {
        // 相同:直接调用
        next.invokeChannelRead(msg);
    } else {
        // 不同:将任务提交给下一个 handler 的线程执行(换人)
        executor.execute(new Runnable() {
            @Override
            public void run() {
                next.invokeChannelRead(msg);
            }
        });
    }
}

换人机制

  1. 同一个线程:直接调用下一个 handler
  2. 不同线程:将任务封装后提交给下一个 handler 的线程

示例:

Handler1 (NIO EventLoop-1) 
    ↓ 检测到 Handler2 属于不同线程
    ↓ 将任务提交给 普通 EventLoop-3
Handler2 (普通 EventLoop-3) 执行

八、EventLoop 处理普通任务

示例:提交普通任务

NioEventLoopGroup nioWorkers = new NioEventLoopGroup(2);

log.debug("server start...");
Thread.sleep(2000);

// 提交普通任务
nioWorkers.execute(() -> {
    log.debug("normal task...");
});

输出:

22:30:36 [DEBUG] [main] - server start...
22:30:38 [DEBUG] [nioEventLoopGroup-2-1] - normal task...

使用场景

  • 执行耗时较长的任务(避免阻塞 I/O 线程)
  • 数据库查询、文件操作等

九、EventLoop 处理定时任务

示例:提交定时任务

NioEventLoopGroup nioWorkers = new NioEventLoopGroup(2);

log.debug("server start...");
Thread.sleep(2000);

// 提交定时任务(每隔 1 秒执行一次)
nioWorkers.scheduleAtFixedRate(() -> {
    log.debug("running...");
}, 0, 1, TimeUnit.SECONDS);

输出:

22:35:15 [DEBUG] [main] - server start...
22:35:17 [DEBUG] [nioEventLoopGroup-2-1] - running...
22:35:18 [DEBUG] [nioEventLoopGroup-2-1] - running...
22:35:19 [DEBUG] [nioEventLoopGroup-2-1] - running...
22:35:20 [DEBUG] [nioEventLoopGroup-2-1] - running...
...

使用场景

  • 心跳检测
  • 定时清理缓存
  • 定时统计数据

十、总结

EventLoop 核心概念

概念说明
EventLoop单线程执行器 + Selector,处理 I/O 事件、普通任务、定时任务
EventLoopGroupEventLoop 的集合,负责管理多个 EventLoop
Channel 绑定每个 Channel 绑定到一个 EventLoop,保证线程安全
分工机制NIO EventLoop 处理 I/O,普通 EventLoop 处理业务逻辑
换人机制不同线程的 handler 通过任务提交实现切换

EventLoop 的三大能力

  1. 处理 I/O 事件:读写数据、连接管理
  2. 执行普通任务:用户自定义任务
  3. 执行定时任务:周期性任务

最佳实践

  1. Boss Group 使用 1 个线程:只负责接收连接
  2. Worker Group 使用多个线程:处理多个客户端的 I/O
  3. 耗时任务使用独立的 EventLoopGroup:避免阻塞 I/O 线程
  4. 优雅关闭:使用 shutdownGracefully() 确保任务完成

十一、图解总结

单 EventLoopGroup 模式

ServerBootstrap
    ↓
EventLoopGroup (2个线程)
    ├── EventLoop-1 → Channel-1, Channel-3
    └── EventLoop-2 → Channel-2

双 EventLoopGroup 模式(推荐)

ServerBootstrap
    ├── Boss Group (1个线程)
    │   └── EventLoop-Boss → 监听端口,接收连接
    │
    └── Worker Group (2个线程)
        ├── EventLoop-1 → Channel-1 (I/O 处理)
        └── EventLoop-2 → Channel-2 (I/O 处理)

三 EventLoopGroup 模式(分工)

ServerBootstrap
    ├── Boss Group (1个线程)
    │   └── EventLoop-Boss → 监听端口
    │
    ├── Worker Group (2个线程,NIO)
    │   ├── EventLoop-1 → Channel-1 (I/O 处理)
    │   └── EventLoop-2 → Channel-2 (I/O 处理)
    │
    └── Business Group (2个线程,普通)
        ├── EventLoop-3 → 业务逻辑处理
        └── EventLoop-4 → 业务逻辑处理
Netty面试深度解析:从核心原理到实战应用,助你拿下Java后端Offer 在网络编程领域,I/O模型和并发处理是构建高性能服务的基础。Java NIO提供了非阻塞I/O能力,但其原生API复杂且易错。Netty作为异步事件驱动框架,通过Reactor线程模型和高效的内存管理机制,解决了高并发场景下的性能与开发效率问题。其核心价值在于提供了易于扩展的管道处理器链(ChannelPipeline)和零拷贝优化,显著提升了网络应用的吞吐量与响应速度。这些特性使其在RPC框架通信层、即时通讯、物联网等需要处理海量连接与数据的应用场景中成为首选技术。本文聚焦于Netty的线程模型与内存管理 阅读详情

相关推荐

2-Netty核心组件详解

Netty核心组件解析与最佳实践 本文深入剖析Netty的核心组件架构与工作机制,主要包括以下要点: 组件关系:详细展示EventLoopGroup、EventLoop、Channel及Pipeline的绑定关系和工作流程 EventLoop核心: 单线程处理多Channel的IO事件 串行执行保证线程安全 避免阻塞的最佳实践方案 ByteBuf机制: 内存结构与读写操作示例 堆内存与直接内存的性能对比 引用计数管理策略 异步编程: ChannelFuture回调处理 异常处理与重连机制 超时控制实现方案

White Chuan 18

【Netty核心原理】篇二:核心组件“全家福”——Channel、EventLoop与ChannelHandler详解

理解它们之间的关系,就如同掌握了Netty的“设计图纸”,能够让我们在复杂业务场景下游刃有余,精准定位性能瓶颈,构建出稳定可靠的高性能网络应用。理解这三者之间的关系与协作模式,是摆脱“复制粘贴”式使用Netty,进而能够针对复杂业务场景进行定制化开发和深度优化的关键。Pipeline是连接Channel、EventLoop和ChannelHandler的纽带,它是一个双向链表结构,维护着所有的ChannelHandler。是Netty提供的一个精巧的负载控制参数,用于平衡IO处理与任务处理的时间分配。

持续输出Java相关知识 4664

深入Netty源码:构建高性能网络应用的权威指南

Netty是一个高性能、异步事件驱动的网络应用框架,专为快速开发可维护的高性能协议服务器和客户端而设计。其最初由JBOSS的Jens Schauder和Norman Maurer创建,目的是解决在网络编程中遇到的种种问题。如今,Netty已被广泛应用于互联网通信领域,如游戏服务器、即时通讯、分布式服务框架等,成为IT行业网络编程的事实标准之一。在现代的网络编程中,异步事件驱动架构已经成为了构建高性能、可扩展的网络服务的标准模式。

weixin_42581846的博客 718

深入剖析 Netty 的核心组件

本篇文章对 Netty 中开发者最经常打交道的五个组件:ByteBuf,Channel,pipeline,ChannelHandler、EventLoop 做了详细的说明...

形势所逼,不进则退 270

电路课设-音响分频器电路设计

(一)题目简介 1.一阶分频器电路设计 假定高音和低音扬声器均等效为 16 欧姆电阻,设计如图 2 的简单分频器电 路,要求高低频分界(两个滤波器的截止频率)为 5kHz。 1) 写出高音扬声器和低音扬声器电压对于 vs 的传递函数,确定电路中电 容 C 和电感 L 的元件值;2)利用 AC 频率扫描分析求出两个扬声器电压的频率响应曲线,验证计算 结果。用包含高低频成分的电压 vs 激励进行测量验证。 3)计算并利用 EWB 仿真证明从 vs 看进去的阻抗为一常数 16 欧姆。

weixin_53507617的博客 1万+

C#程序突然崩溃怎么办?5分钟学会分析Dump文件(Visual Studio 2022实战)

本文详细介绍了在C#程序崩溃或无响应时,如何捕获并分析Dump文件以快速定位问题。通过Visual Studio 2022实战演示,重点讲解了配置符号服务器、解读调用堆栈与内存状态,以及针对CPU飙高、内存泄漏等典型场景的分析方法,帮助开发者高效进行故障诊断。

docker8compose的博客 474

Netty中的EventLoop是什么,它的工作原理是什么?

EventLoop是 Netty 中的核心组件,通过单线程或多线程的方式管理 I/O 事件和任务调度。它的工作原理包括事件循环、任务队列、事件处理和任务执行。通过合理配置和使用EventLoop,可以实现高效、非阻塞的网络编程。

qq_33240556的博客 436

Ansys Lumerical 启动时出现 Error: Could not connect to Ansys license server specified at 1055@ 的另一种解决办法

昨天在关闭了中之后 就能正常打开 FDTD 了,结果今天想开启出现了同样的报错:我猜测昨天能启动的原因在于关闭之后要重启电脑,并且在重启之后我第一时间打开 lumerical 测试因此端口没有被占用,今天是在电脑启动之后一段时间才打开所以又遇到了端口占用的问题。

qq_51404184的博客 9558

《Netty实战》总结

前言 我们都知道Netty是一款用于创建高性能网络应用程序的高级框架,但是实际工作中真正地去直接使用Netty的场景好像不多(反正我没有)。其实Netty无处不在,很多中间件底层通信框架用的都是Netty,dubbo、rocketMQ、Elasticsearch等常用的框架和中间件其实都用到了Netty。最近在读《Netty实战》这本书,做一个知识点的简要概括吧,省略了一些章节(比如Netty用于...

Forest441的博客 1087

五、2K0300 久久派开发板的GPIO控制与Shell脚本自动化实战

本文详细介绍了基于龙芯2K0300处理器的久久派开发板的GPIO控制方法,通过sysfs文件系统实现LED控制和传感器读取。重点讲解了Shell脚本自动化实战,包括LED闪烁、流水灯效果和传感器数据采集,为物联网项目开发提供完整解决方案。

silver的专栏 689

[QMT量化交易小白入门]-五十、十年基本保证每年盈利,全天ETF候稳稳的幸福

全局参数raise_rate = -1 # 触发rebalance的上涨比例period: 设定为22,表示每22个交易日执行一次调仓(即大约每月一次)。这是策略的时间框架基础。raise_rate: 初始值设为-1,意味着默认情况下不会因为资产的涨幅而触发调仓。这一参数用于控制是否基于资产表现动态调整仓位。run_count: 用于记录策略运行的次数,帮助判断何时执行定期调仓。1、为了简便计算,回撤时将调仓再平衡是先卖出再买入,没有比较持仓,实盘时是需要计算的,减少交易费用。

木头大左的博客 808

《netty实战》读书笔记四---心跳、编码解码、TCP 粘包和拆包 及解决方案

netty心跳 IdelStateHandler http是无状态,Http协议是无状态的, 浏览器和服务器间的请求响应一次,下一次会重新创建连接,webSocket的长连接的全双工的交互,改变Http协议多次请求的约束,实现长连接了, 服务器可以发送消息给浏览器 http传输过程中是分段的,HttpObjectAggregator可以将多个段聚合 浏览器在发送大量数据的时候,就会发出多次...

阿拉斯加大闸蟹的博客 1736

机床联网系列总结

总结机床联网专栏,两个好用的工具介绍,以及后续提升的方法和建议。

若云流风的专栏 934

netty简介和使用

用一句简单的话来说就是:Netty封装了JDK的NIO,让你用得更方便,不用再写一大堆复杂的代码了1.对 Java 的 NIO 进行了封装,屏蔽了 NIO 使用的复杂性,简化了网络通信的开发。2.支持众多协议,不仅仅 HTTP、HTTP2、DNS、Redis 协议等等。3.极大地简化并优化了 TCP 和 UDP 套接字服务器等网络编程,并且性能以及安全性等很多方面甚至都要更好。网络编程需要考虑粘包和拆包问题,连接的管理,编解码的处理,Netty都为你定制好了,开箱即用。...

时光的博客 716

基于 SoC 的卷积神经网络车牌识别系统设计(1)引言

通过 CPU 软核 IP 在纯 FPGA 平台上构建一个 AI SoC 卷积神经网络车牌识别系统,其中,缩放、填充层、卷积层、ReLU、池化层、全连接层 IP 都是 Verilog 设计的,同时集成了各种高性能的 IP。这是最具挑战性的 AI SoC 芯片设计项目,集成了 Python 卷积神经网络代码、Verilog 卷积神经网络硬件设计、ARM SoC 设计、ARM 与 FPGA 的交叉编译流程等等。这不仅是科研学习、集创竞赛、秋招求职的一个极具优势的精彩项目,也是目前最火热的芯片行业之中的一个...

新芯设计的博客 3783

2024华为OD机试真题-矩阵匹配-C++-OD统一考试(C卷D卷)

​从一个 N * M(N ≤ M)的矩阵中选出 N 个数,任意两个数字不能在同一行或同一列,求选出来的 N 个数中第 K 大的数字的最小值是多少。输入描述输入矩阵要求:1 ≤ K ≤ N ≤ M ≤ 150

goldarmour的博客 279

Netty 核心原理与优化机制笔记

需要 2 次 CPU 拷贝(内核→用户,用户→内核)只需 1 次 CPU 拷贝(内核→堆外内存),避免了用户堆内存的额外拷贝0 次 CPU 拷贝,完全零拷贝,效率最高线程模型优化:多线程 + 多路复用(EventLoopGroup + Selector)责任链解耦:ChannelPipeline 管理编码、解码和业务处理器零拷贝技术:DirectByteBuffer 降低拷贝,FileRegion 利用 sendfile 彻底零拷贝。

fqlya的博客 867

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Netty之旅总览

一篇文章入门Netty ByteBuf详解 ChannelHandler流程详解 EventLoop流程详解 Bootstrap使用详解 ChannelHandler做测试 数据格式转换与自带Channel工具 Netty Hello world版启动源码分析 ...

weixin_34174132的博客 94

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

【Netty】四.Netty异步编程模型深度解析

摘要:本文深入解析Netty异步编程模型,对比同步/异步编程优劣,剖析JDK Future的局限性及Netty的改进方案。重点讲解ChannelFuture和Promise的实现原理,包括状态管理、监听器机制和链式调用。通过源码分析DefaultPromise的核心逻辑,演示异步编程实践案例,并指出sync与await的区别及死锁规避方法。最后给出可靠异步客户端的完整实现方案,涵盖连接重试、心跳检测等关键机制,为构建高性能网络应用提供参考。

hrh的博客 834

学习使用netty

学习使用netty netty详细介绍1:https://www.infoq.cn/article/netty-high-performance/#anch111813 netty详细介绍2:https://blog.youkuaiyun.com/sun7545526/category_7685695.html netty使用:https://blog.youkuaiyun.com/haoyuyang/article/d...

sqlgao22的博客 355

阿里大牛带你快速搞懂netty,面试大厂再也不怕被问netty了

前言: 花了三天时间总算把netty的知识点总结出来了,现在分享给你们,面试大厂在也不要怕了,直接吊打面试官。 如果你们觉得我总结的不错的话,给我一个小心心鼓励一下吧,话不多说,我们开始正题。 IO模型 IO模型就是说用什么样的通道进行数据的发送和接收,Java共支持3种网络编程IO模式:BIO,NIO,AIO BIO(Blocking IO) 同步阻塞模型,一个客户端连接对应一个处理线程 缺点: 1、IO代码里read操作是阻塞操作,如果连接不做数据读写...

weixin_56412033的博客 480

《Netty实战》读书笔记

第一部分 Netty 的概念及体系结构 《第一章 Netty-异步事件驱动》 (1)异步和事件驱动 异步、异步方法会立即返回,非阻塞网络的调用使我们不必等待一个操作的完成 选择器使得我们能够通过较少的线程便可监视许多连接上的事件。 (2)Netty核心组件 channel、NIO的基本构造负责连接以及缓冲区数据的传输 回调、Netty内部使用回调处理事件,例如一个新的连接建立的时候Cha...

郭敬仰的博客 719

深入Netty核心:高性能网络编程架构、内存管理与生产实践

网络编程是构建分布式系统的基石,其核心在于高效处理海量并发连接与数据交换。事件驱动与异步非阻塞IO模型通过Reactor模式实现,将IO事件的检测与业务处理分离,从而大幅提升资源利用率与吞吐量。这一原理在高性能网络通信框架中至关重要,直接决定了服务的响应能力与扩展性。Netty作为Java领域高性能网络通信的事实标准,其价值在于通过精妙的线程模型、零拷贝技术和内存池化机制,为构建网关、RPC框架、即时通讯等低延迟、高并发场景提供了强大支撑。本文聚焦Netty的核心架构,深入剖析其事件循环、ByteBuf内存

weixin_33901641的博客 361

突破Netty极限:基于Java 21 FFM API手写高性能网络通信框架

在 C 语言中,是网络编程的基础。在 FFM 中,我们需要用来精确描述内存布局。/*** 示例 5: 定义 C 结构体 struct sockaddr_in// 2 bytes// 2 bytes// 4 bytes// 8 bytes* };*/// 定义内存布局ValueLayout.JAVA_SHORT.withByteAlignment(2).withName("sin_port"), // 网络字节序,需注意// 设置协议族 AF_INET = 2。

fuladulu的博客 233

Netty——核心组件

JAVA后端开发知识总结(持续更新…) Netty—— 文章目录Netty——一、Netty核心组件1.1 Bootstrap 和 ServerBootstrap 一、Netty核心组件 1.1 Bootstrap 和 ServerBootstrap 一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件。 Netty 中 Bootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端启动引导类。 ...

weixin_43415481的博客 333

Netty学习专栏(二):Netty快速入门及重要组件详解(EventLoop、Channel、ChannelPipeline)

本文介绍Netty通过三大核心组件构建高性能网络框架:EventLoop实现主从Reactor线程模型,高效调度I/O事件与异步任务;Channel统一封装TCP/UDP等协议操作,支持零拷贝传输;ChannelPipeline以双向责任链串联编解码、业务逻辑等Handler,实现模块化数据处理。三者协同解决传统NIO的线程管理复杂、扩展性差等痛点,提升开发效率与吞吐量。

qq_43947876的博客 1043
上一篇: Netty源码分析---netty-init()方法解析
下一篇: Netty编码器深度解析-详细版
不早睡不改名@
博客等级 码龄5年 536粉丝 306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值